본문 바로가기

Language/python

그냥.. Producer/Consumer Python 예제


import Queue
import copy
import threading
import time

mq = Queue.Queue(256)
mtx_print = threading.RLock()

def safe_print(str):
    mtx_print.acquire(True)
    print str
    mtx_print.release()

class ProducerThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
   
    def run(self):
        a = [1,2,3]
       
        for i in range(10):
            mq.put(copy.deepcopy(a), True, 1)
            safe_print("Producer : Sent %d" % (i+1))
            time.sleep(1)
            a[0] = a[0] + 1
   
class ConsumerThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
   
    def run(self):
        i = 0
        while True:
            list = mq.get(True)
            safe_print("Consumer : Got %d" % (list[0]))
            i = i + 1
           
            if i == 10:
                break

if __name__ == '__main__':
    p_thread = ProducerThread()
    c_thread = ConsumerThread()
   
    print "Thread Start"
    p_thread.start()
    c_thread.start()
   
    print "Wait..."
    p_thread.join()
    c_thread.join()
   
    print "End"