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():
flag=threading.Condition()
First=first(flag,Second)
First.start()
Second=second(flag,First)
Second.start()
I get an error when I do the above.
You can use the Queue module: Give each of your threads a
Queue.Queueobject. 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.