Does anybody know how I can send a variable (or get a variable) from threadOne to threadTwo in this code without using a global variable? If not, how would I operate a global variable? Just define it before both classes and use the global definition in the run function?
import threading
print "Press Escape to Quit"
class threadOne(threading.Thread): #I don't understand this or the next line
def run(self):
setup()
def setup():
print 'hello world - this is threadOne'
class threadTwo(threading.Thread):
def run(self):
print 'ran'
threadOne().start()
threadTwo().start()
Thanks
You can use queues to send messages between threads in a thread safe way.
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()
q = Queue()
for i in range(num_worker_threads):
t = Thread(target=worker)
t.daemon = True
t.start()
for item in source():
q.put(item)
q.join() # block until all tasks are done
Here you go, using Lock
.
import threading
print "Press Escape to Quit"
# Global variable
data = None
class threadOne(threading.Thread): #I don't understand this or the next line
def run(self):
self.setup()
def setup(self):
global data
print 'hello world - this is threadOne'
with lock:
print "Thread one has lock"
data = "Some value"
class threadTwo(threading.Thread):
def run(self):
global data
print 'ran'
print "Waiting"
with lock:
print "Thread two has lock"
print data
lock = threading.Lock()
threadOne().start()
threadTwo().start()
Using global variable data
.
The first thread acquires the lock and write to the variable.
Second thread waits for data and prints it.
Update
If you have more than two threads which need messages to be passed around, it is better to use threading.Condition
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With