2014-04-19 116 views
-1

我有一個listn線程。我想用一些IPC機制以某種順序追加到這個列表中,順序是第一個線程先寫入list,然後寫入第二個線程等。 我唯一想到的就是使用n個鎖和解鎖另一個線程的鎖之前完成其任務,但我不相信這是正確的解決方案。謝謝你的幫助。按順序執行python線程

+0

在何種意義上,你認爲這個解決方案是 「不正確」? – NPE

+0

請試用一些代碼片段,看看它是不是一個正確的解決方案。 :) –

+1

你應該先嚐試....你應該只相信你所看到的... 我知道它的初衷是不確定一個解決方案,並仍然嘗試它......但它付出很好:) – adil

回答

0

您可以使用隊列模塊做到這一點:

from Queue import * 
from threading import Thread, Lock 

# this function will process the items in the queue, in serial 
def processor(): 
    if queue.empty() == True: 
     print "the Queue is empty!" 
     sys.exit(1) 
    try: 
     job = queue.get() 
     print "I'm operating on job item: %s"%(job) 
     queue.task_done() 
    except: 
     print "Failed to operate on job" 

# set variables 
queue = Queue() 
threads = 4 

''' a list of job items. you would want this to be more advanced, 
like reading from a file or database''' 
jobs = [ "job1", "job2", "job3" ] 

# iterate over jobs and put each into the queue in sequence 
for job in jobs: 
    print "inserting job into the queue: %s" % (job) 
    queue.put(job) 

# start some threads, each one will process one job from the queue 
for i in range(threads): 
    th = Thread(target=processor) 
    th.setDaemon(True) 
    th.start() 

# wait until all jobs are processed before quitting 
queue.join() 
有關隊列模塊

更多信息,有一個在頁面的末端神例如: https://docs.python.org/2/library/queue.html

@EDIT 您可以使用a QueueFIFO(先進先出)或LIFO(後進先出)。

FIFO例如:

import Queue 

q = Queue.Queue() 

for i in range(5): 
    q.put(i) 

while not q.empty(): 
    print q.get() 

>>> 0 
>>> 1 
>>> 2 
>>> 3 
>>> 4 

LIFO

import Queue 

q = Queue.LifoQueue() 

for i in range(5): 
    q.put(i) 

while not q.empty(): 
    print q.get() 

>>> 4 
>>> 3 
>>> 2 
>>> 1 
>>> 0