2013年9月14日 星期六

Sending messages between class threads Python


inf : http://stackoverflow.com/questions/14508906/sending-messages-between-class-threads-python

ref : http://www.rabbitmq.com/tutorials/tutorial-two-python.html

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

import threading

print "Press Escape to Quit"

# Global variable
data = None

class threadOne(threading.Thread): 
    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()

沒有留言:

張貼留言