Created
November 17, 2011 16:42
-
-
Save yatt/1373686 to your computer and use it in GitHub Desktop.
producer consumer problem
This file contains hidden or 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
| from multiprocessing import Queue as mQueue, Process | |
| from multiprocessing.sharedctypes import Value | |
| import ctypes | |
| import time | |
| import random | |
| def consumer(i, q): | |
| while True: | |
| item = q.get() | |
| if item is None: | |
| print '[C%d]: end' % i | |
| q.put(None) | |
| break | |
| time.sleep(3) | |
| print '[C%d]: consume %d' % (i, item) | |
| def producer(i, q, isend): | |
| n = 1 | |
| while True: | |
| print '[P%d]: produce %d' % (i, n) | |
| q.put(n) | |
| if isend.value == 1: | |
| break | |
| time.sleep(2) | |
| n += 1 | |
| print '[P%d]: end' % i | |
| isend = Value(ctypes.c_int, 0) | |
| q = mQueue() | |
| cs = [Process(target=consumer, args=(i, q)) for i in range(3)] | |
| ps = [Process(target=producer, args=(i, q, isend)) for i in range(3)] | |
| for c in cs: | |
| c.start() | |
| for p in ps: | |
| p.start() | |
| raw_input() | |
| # finalize | |
| isend.value = 1 | |
| for p in ps: | |
| p.join() | |
| for i in range(10): | |
| q.put(None) | |
| for c in cs: | |
| c.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment