2014-04-19 119 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