2016-12-05 159 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

好的這是我想的正確答案,我會嘗試,如果它不起作用,這意味着我使用的機器會由於其他內部原因而崩潰,但我認爲這段代碼是正確的,所以謝謝! –