Created
July 20, 2016 06:27
-
-
Save miminus/370bb2a31e1afd6f9b733d411559e7fb to your computer and use it in GitHub Desktop.
* 如何使用 Queue 来实现 生产者-消费者的关系 * 理解如何使用 task_done()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
######################################################################## | |
# | |
# Copyright (c) 2016 Baidu.com, Inc. All Rights Reserved | |
# | |
######################################################################## | |
""" | |
File: worker_costumer.py | |
Author: mijianhong(mijianhong@baidu.com) | |
Date: 2016/07/18 15:52:30 | |
""" | |
from Queue import Queue | |
from threading import Thread | |
import time | |
def do_work(args): | |
print args | |
def worker(): | |
while True: | |
item = q.get() | |
do_work(item) | |
q.task_done() # task_done() | |
q = Queue() | |
num_worker_threads = 5 | |
for i in range(num_worker_threads): | |
t = Thread(target=worker) | |
t.daemon = True | |
t.start() | |
for item in [1,2,3,4,5]: | |
q.put(item) | |
time.sleep(0.1) | |
print 'item:' + str(item) | |
print 'starting waiting...' | |
time.sleep(2) | |
q.join() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment