Take the 2-minute tour ×

I have two threads and both the threads do a set of calculations and obtain results. The problem is at one point both the thread's calculations require the results obtained in the other. I thought of inheritance but could only pass values from one thread to another. How can I pass values between two threads without using a global variable?

I want to do something like this.

class first(threading.Thread):
    def __init__(self, flag, second):
    ##rest of the class first##

class second(threading.Thread):
    def __init__(self, flag, first):
    ##rest of the class second##

def main():

I get an error when I do the above.

share|improve this question
Side note: you mention that you do calculations: if you use the CPython implementation of Python, then you are likely not going to really gain anything from using threads, as calculation threads mostly do not run simultaneously, with the CPython interpreter (because of the famous Global Interpreter Lock). You might want to use the multiprocessing module instead, which does not suffer from this problem (communication between processes might be relatively slow, though). –  EOL Aug 28 '12 at 13:53
There are calculations and other operations, basically I/O and list manipulation. –  sHoM Aug 28 '12 at 14:03
add comment

1 Answer

up vote 3 down vote accepted

You can use the Queue module: Give each of your threads a Queue.Queue object. Then each thread can do its calculations, put the result in the other thread's queue and then listen on its own queue until the result of the other thread arrives.

Make sure to post the result first and then wait for the other thread's result, otherwise your threads will end up deadlocked.

share|improve this answer
Won't it give 'referenced before assignment' error? Because First thread is launched before Second. –  sHoM Aug 28 '12 at 14:05
No, because you'll create the queue from the main thread (the thread that creates the other threads). –  Jeff Foster Aug 28 '12 at 14:09
add comment

Your Answer


