代码改变世界

python queue

2017-11-16 11:17  woodzcl  阅读(317)  评论(0编辑  收藏  举报

python中的队列,自带有同步锁原语,可以直接用来同步线程的执行,前提是把需要处理的数据放入队列中,然后各个线程独立从队列中取出数据处理

//test.py

import Queue

import threading

import time

 

exitFlag = 0

 

class myThread (threading.Thread):

    def __init__(self, threadID, name, q):

        threading.Thread.__init__(self)

        self.threadID = threadID

        self.name = name

        self.q = q

    def run(self):

        print "Starting " + self.name

        process_data(self.name, self.q)

        print "Exiting " + self.name

 

def process_data(threadName, q):

    while not exitFlag:

        if not workQueue.empty():

            data = q.get()

            print "%s processing %s" % (threadName, data)

        time.sleep(1)

 

workQueue = Queue.LifoQueue(10)

 

nameList = ["One", "Two", "Three", "Four", "Five"]

for word in nameList:

    workQueue.put(word)

 

threads = []

threadID = 1

threadList = ["Thread-1", "Thread-2", "Thread-3"]

for tName in threadList:

    thread = myThread(threadID, tName, workQueue)

    thread.start()

    threads.append(thread)

    threadID += 1

 

while not workQueue.empty():

    pass

 

exitFlag = 1

 

for t in threads:

    t.join()

print "Exiting Main Thread"

 

//result

# python test.py
Starting Thread-1
Thread-1 processing Five
Starting Thread-2
Thread-2 processing Four
Starting Thread-3
Thread-3 processing Three
Thread-1 processing Two
Thread-2 processing One
Exiting Thread-1
Exiting Thread-2
Exiting Thread-3
Exiting Main Thread

Finally:

学习新语言的目的有两个

1. 看看所谓的新语言都新在哪里了

2. 回头看看古代语言(C/C++)中,你是否如此这般的用对用巧了,比如这里的线程和队列

 

所谓,“签进的同时也是离不开后退”,就是这个道理