Skip to content

Instantly share code, notes, and snippets.

@miminus
Created July 20, 2016 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miminus/370bb2a31e1afd6f9b733d411559e7fb to your computer and use it in GitHub Desktop.
Save miminus/370bb2a31e1afd6f9b733d411559e7fb to your computer and use it in GitHub Desktop.
* 如何使用 Queue 来实现 生产者-消费者的关系 * 理解如何使用 task_done()
#!/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