2017-04-05 1 views
0

다른 모듈의 메서드를 실행하는 다른 스레드로 전달할 부울이 있습니다. 이 부울은 취소 토큰의 역할을하므로 설정되면 스레드가 종료됩니다. 다른 스레드에서 설정하면 다른 스레드에서 변경되지 않으므로 값으로 전달 된 것 같습니다. 감사.스레드와 모듈을 통해 참조로 부울을 전달하는 방법

import module2 
from threading import Thread 

cancellationToken = False 

def main: 
    thread2 = Thread(target = module2.method2, args (on_input, cancellationToken,)) 
    thread2.start() 
    ... 
    thread2.join() 

def on_input(command): 
    global cancellationToken 
    ... 
    if(...): 
     cancellationToken = True 
    ... 

module2의 method2는 취소 토큰을 확인하고 사용자 입력에 응답하는 단순한 무한 루프입니다.

def method2(on_input, cancellationToken): 
    while(True): 
     if(cancellationToken): 
      return 
     ... 
     on_input(...) 
+0

, 당신은'Event' 객체를 사용할 수 있습니다 : https://docs.python.org/3.4/library/threading.html#event-objects –

답변

2

당신이 할 때 :

thread2 = Thread(target = module2.method2, args (on_input, cancellationToken,)) 

당신은 본질적으로 스레드 방법 2 인자의 값 False을 전달하고 있습니다.

하지만 당신은 그 후이 작업을 수행 할 때

cancellationToken = True 

당신은 cancellationToken으로 표시 기준을 대체하고 있지만 원래 thread2에 전달 된 값입니다. 당신이 원하는 것을 달성하기

, 당신은 당신의 취소 상태에 대한 변경 가능한 객체 랩퍼를 작성해야합니다 :

class CancellationToken: 
    def __init__(self): 
     self.is_cancelled = False 

    def cancel(self): 
     self.is_cancelled = True 

cancellationToken = CancellationToken() 

thread2 = Thread(target = module2.method2, args (on_input, cancellationToken,)) 

# then later on 
cancellationToken.cancel() 

스레드 코드가됩니다 : 간단한 부울

def method2(on_input, cancellationToken): 
    while(True): 
     if(cancellationToken.is_cancelled): 
      return 
     ... 
     on_input(...) 
관련 문제