Created
June 21, 2012 12:22
-
-
Save rswofxd/2965459 to your computer and use it in GitHub Desktop.
Python:线程,队列运用
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
#coding=utf-8 | |
import threading, Queue | |
import time, random | |
""" | |
线程,队列同步运用 | |
""" | |
############## | |
# Producer thread | |
############## | |
class Producer(threading.Thread): | |
def __init__(self, threadname, queue): | |
threading.Thread.__init__(self, name = threadname) | |
self.sharedata = queue | |
def run(self): | |
for i in range(20): | |
print(self.getName(),'adding',i,'to queue') | |
self.sharedata.put(i) | |
time.sleep(random.randrange(10)/10.0) | |
print(self.getName(),'Finished') | |
############### | |
# Consumer thread | |
############### | |
class Consumer(threading.Thread): | |
def __init__(self, threadname, queue): | |
threading.Thread.__init__(self, name = threadname) | |
self.sharedata = queue | |
def run(self): | |
for i in range(20): | |
print(self.getName(),'got a value:',self.sharedata.get()) | |
time.sleep(random.randrange(10)/10.0) | |
print(self.getName(),'Finished') | |
############ | |
# Main thread | |
############ | |
def main(): | |
queue = Queue.Queue() | |
producer = Producer('Producer', queue) | |
consumer = Consumer('Consumer', queue) | |
print ('Starting threads ...') | |
producer.start() | |
consumer.start() | |
producer.join() | |
consumer.join() | |
print ('All threads have terminated.') | |
################################################# | |
#测试代码 | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment