Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending messages between class threads Python

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

like image 396
Sam Heather Avatar asked Jan 24 '13 19:01

Sam Heather


2 Answers

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
like image 164
gak Avatar answered Nov 01 '22 20:11

gak


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.

like image 41
ATOzTOA Avatar answered Nov 01 '22 20:11

ATOzTOA