2016-12-05 160 views
0

我想运行2个线程,第一个函数有一个函数目标,这个函数应该从机器读取一个值,当这个值= 0时,输出0保存在一个数组中。当这个值不再为0时,输出1应该保存在这个数组中。然后队列必须返回这个列表。第二个线程有一个函数2作为目标,而这个函数正在做其他事情。我会尝试在以下代码中显示它:当另一个线程完成时停止线程。

import threading 
from multiprocessing import Queue 
def func1(queue_in): 
    list=[] 
    while value_from_machine==0: #this value will always be refreshed and read again 
     list.append(0) 
     queue_in.put(list) 
    list.append(1) #when the value from the machine is not 0 anymore, put a 1 in the list 
    queue_in.put(list) 

def func2(): 
    #doing something else... 

q_out=Queue() 

thread1=threading.Thread(target=func1,args=(q_out)) 
thread2=threading.Thread(target=func2) 

thread1.start() 
thread2.start() 

q_value=q_out.get() 

if sum(q_value)==1: 
    #print something 
else: 
    #print something else 

现在问题是我想在第二个线程完成时停止第一个线程。另一件事是我不知道是在第一个函数队列作为输出。在while循环中有一个队列是否好?

回答

1

标准方法怎么样 - 设置Event

from threading import Thread, Event 
from Queue import Queue 
from time import sleep 

def func1(queue_in, done): 
    while not done.is_set(): 
     queue_in.put_nowait(1) 
     print 'func1 added new item to the queue_in' 
     sleep(1) 
    print 'func1 has finished' 

def func2(done): 
    x = 0 
    while x < 3: 
     sleep(2) 
     x += 1 
     print 'func2 processed %s item(s)' % x 
    print 'func2 has finished' 
    done.set() 

q_out = Queue() 
done = Event() 

thread1 = Thread(target=func1, args=[q_out, done]).start() 
thread2 = Thread(target=func2, args=[done]).start() 

输出:

func1 added new item to the queue_in 
func1 added new item to the queue_in 
func2 processed 1 item(s) 
func1 added new item to the queue_in 
func1 added new item to the queue_in 
func2 processed 2 item(s) 
func1 added new item to the queue_in 
func1 added new item to the queue_in 
func2 processed 3 item(s) 
func2 has finished 
func1 has finished 
+0

不应事件名称给出的第一个函数中的参数?那么它将在第一个线程中作为参数给出 –

+0

事实上,通过函数参数传递'Event'会更好。我更新了我的答案,向您展示任务工作流程。 –

+0

好的这是我想的正确答案,我会尝试,如果它不起作用,这意味着我使用的机器会由于其他内部原因而崩溃,但我认为这段代码是正确的,所以谢谢! –