2016-12-05 1 views
0

2 개의 스레드를 실행하려고하는데 첫 번째 스레드는 function1 대상을 갖고이 함수는 기계에서 값을 읽어야하며이 값이 0 인 동안 출력 0은 배열에 저장됩니다. 이 값이 더 이상 0이 아니면 출력 1을이 배열에 저장해야합니다. 그런 다음 대기열에서이 목록을 반환해야합니다. 두 번째 스레드는 function2를 대상으로하며이 함수는 다른 작업을 수행합니다. 다음 코드에서 보여하려고합니다 : 다른 스레드가 완료되면 스레드를 중지합니다.

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

괜찮아요. 제 생각에는 정답입니다. 시도해 보겠습니다. 작동하지 않는다면, 이것은 다른 내부적 인 이유로 인해 제가 사용하고있는 기계가 추락 할 것이라는 것을 의미합니다.하지만이 코드가 맞다고 생각합니다. 감사합니다! –

관련 문제