참고: http://docs.python.org/library/queue.html?Queue.Queue
python에선 multi-thread에 이용하기 편하도록, synchronized queue 객체를 제공함.
ex) queue를 이용한 multi thread 생산자-소비자 모델
- 경쟁적으로 queue에 마구 넣고, 마구 뽑지만 deadlock이나 충돌같은 건 발생하지 않음.
thread 내에서 lock을 걸고 할 필요가 없으므로 상대적으로 깔끔한 코드가 나옴.
#!/usr/bin/python
import threading, time, random
from Queue import Queue
# 소비자 10
CONSUMER_COUNT = 10
# 생산자 5
PRODUCER_COUNT = CONSUMER_COUNT / 2
# 저장공간이 10인 queue 생성
q = Queue(10)
class Consumer(threading.Thread):
def run(self):
for i in range(5):
# queue에서 뽑아먹는다
print '[%s] gets %s' % (self.getName(), q.get())
time.sleep(0.0)
class Producer(threading.Thread):
def run(self):
for i in range(10):
# 0~20 사이의 임의의 난수를 queue에 밀어 넣음
randomInt = random.randint(0, 20)
q.put(randomInt)
print '[%s] puts %s ---------------------' % (self.getName(), randomInt)
time.sleep(0.0)
# thread 리스트
con = []
pro = []
# Consumer thread 생성
for i in range(CONSUMER_COUNT):
con.append(Consumer())
# Producer thread 생성
for i in range(PRODUCER_COUNT):
pro.append(Producer())
# Consumer 먼저 시작
for th in con:
th.start()
# Producer 시작
for th in pro:
th.start()
# thread 종료까지 대기
for th in con:
th.join()
for th in pro:
th.join()
print 'Exiting'
import threading, time, random
from Queue import Queue
# 소비자 10
CONSUMER_COUNT = 10
# 생산자 5
PRODUCER_COUNT = CONSUMER_COUNT / 2
# 저장공간이 10인 queue 생성
q = Queue(10)
class Consumer(threading.Thread):
def run(self):
for i in range(5):
# queue에서 뽑아먹는다
print '[%s] gets %s' % (self.getName(), q.get())
time.sleep(0.0)
class Producer(threading.Thread):
def run(self):
for i in range(10):
# 0~20 사이의 임의의 난수를 queue에 밀어 넣음
randomInt = random.randint(0, 20)
q.put(randomInt)
print '[%s] puts %s ---------------------' % (self.getName(), randomInt)
time.sleep(0.0)
# thread 리스트
con = []
pro = []
# Consumer thread 생성
for i in range(CONSUMER_COUNT):
con.append(Consumer())
# Producer thread 생성
for i in range(PRODUCER_COUNT):
pro.append(Producer())
# Consumer 먼저 시작
for th in con:
th.start()
# Producer 시작
for th in pro:
th.start()
# thread 종료까지 대기
for th in con:
th.join()
for th in pro:
th.join()
print 'Exiting'
'Python' 카테고리의 다른 글
paramiko 설치 (0) | 2009.10.09 |
---|---|
[Python] PostgreSQL 사용하기 (0) | 2009.10.05 |
[Python] Queue, Stack (2) | 2009.10.05 |
[Python] threading 객체사용 (5) | 2009.10.05 |
[Python] thread 사용법 (0) | 2009.10.05 |