Reputation: 31
I have a little doubt if one could solve my issue, and create successful communication between threads.
First example and this is how it should be working, but does not work well:
import Queue,threading,time
class th(threading.Thread):
def __init__(self,q):
threading.Thread.__init__(self)
self.q = q
self.t = time
def run(self):
for i in range(5):
self.q.put(i)
self.t.sleep(0.5) # <----------
self.q.put('end')
class main(object):
def __init__(self):
self.q = Queue.Queue()
self.thread = th(self.q)
self.thread.setDaemon(True)
self.thread.run()
self.call()
def call(self):
while True:
recv = self.q.get();
if recv == 'end':
break
else:
print recv
if __name__ == '__main__':
root = main()
root.call()
In this example, all printed at the same time: 0,1,2,3,4
Second example:
import Queue,threading,time
class th(threading.Thread):
def __init__(self,q):
threading.Thread.__init__(self);
self.q = q
self.t = time
def run(self):
for i in range(5):
self.q.put(i) # <------ no sleep()
self.q.put('end')
class main(object):
def __init__(self):
self.q = Queue.Queue()
self.thread = th(self.q)
self.thread.setDaemon(True)
self.thread.run()
self.call()
def call(self):
while True:
recv = self.q.get()
if recv == 'end':
break
else:
print recv
if __name__ == '__main__':
root = main()
root.call()
the code is printed as it has to 0, 1 2 3 4
one to one
is there any way that the sleep
function in the same way?
Upvotes: 0
Views: 108
Reputation: 31
sorry, it was something very simple, really simple, just had to replace
self.thread.run()
by
self.threat.start()
Upvotes: 0
Reputation: 104682
You don't want to call the run
method on a thread directly. Call start
instead, which will kick off the child thread, which will in turn run the run
method.
Your current code is essentially single threaded, since the run
call does the work of the child thread in the parent instead. The child thread is never actually started! (You're also calling your main.call
method twice, which I'd expect to block or raise an exception, but that's a separate issue.)
Upvotes: 2