Mihai Bujanca
Mihai Bujanca

Reputation: 4219

Python threading.Thread() returns NoneType?

I am working on a small application that I know will have 3 threads independent from the main thread, at some point, and I will need to identify a thread from another. Suppose threads are A, B, C. A will need to join with C if something happens. I am trying to add the threads to a dictionary before starting them, so I can identify thread C later:

currentThreads['A'] = threading.Thread(target=func, args=[]]).
currentThreads['A'].start()
currentThreads['B'] = threading.Thread(target=func, args=[]).start()
currentThreads['B'].start()

The behavior is weird: sometimes both currentThreads[key].start() yield AttributeError: 'NoneType' object has no attribute 'start', sometimes only currentThreads['B'].start() does.

Any clue why this might happen?

Upvotes: 0

Views: 1883

Answers (2)

Iron Fist
Iron Fist

Reputation: 10951

I suggest to you, for keeping reference name to your threads, to actually give them names, like so:

t = threading.Thread(name='my_service', target=func)

Then when you need to check for the name of the thread, just get it's name with getName():

current_thread_name =  threading.currentThread().getName() 

Upvotes: 1

Sede
Sede

Reputation: 61273

This is because start returns None so in:

currentThreads['B'] = threading.Thread(target=func, args=[]).start()

currentThreads['B'] is None thus calling currentThreads['B'].start() will raise AttributeError

Upvotes: 2

Related Questions