2016-04-06 20 views
5

Ich habe diesen Code, wie kann ich Func2 von Func1 stoppen? so etwas wie Thread(target = func1).stop() funktioniert nichtStoppt einen Thread Python

import threading 
from threading import Thread 

def func1(): 
    while True: 
     print 'working 1' 

def func2(): 
    while True: 
     print 'Working2' 

if __name__ == '__main__': 
    Thread(target = func1).start() 
    Thread(target = func2).start() 

Antwort

0

Es ist besser, fragen Ihren anderen Thread eine Nachrichten-Warteschlange zum Beispiel zu stoppen, verwenden.

import time 
import threading 
from threading import Thread 
import Queue 

q = Queue.Queue() 

def func1(): 
    while True: 
     try: 
      item = q.get(True, 1) 
      if item == 'quit': 
       print 'quitting' 
       break 
     except: 
      pass 
     print 'working 1' 

def func2(): 
    time.sleep(10) 
    q.put("quit") 
    while True: 
     time.sleep(1) 
     print 'Working2' 

if __name__ == '__main__': 
    Thread(target = func1).start() 
    Thread(target = func2).start() 
+0

zurückkehren machen Aber wenn ich zum Beispiel möchte am Ende des func1 verwenden raw_input. Dann kann func2 func1 nicht schließen. Gibt es dafür eine Lösung? –

0

Sie können einen Thread nicht sagen, zu stoppen, müssen Sie es in der Zielfunktion

from threading import Thread 
import Queue 

q = Queue.Queue() 

def thread_func(): 
    while True: 
     # checking if done 
     try: 
      item = q.get(False) 
      if item == 'stop': 
       break # or return 
     except Queue.Empty: 
      pass 
     print 'working 1' 


def stop(): 
    q.put('stop') 


if __name__ == '__main__': 
    Thread(target=thread_func).start() 

    # so some stuff 
    ... 
    stop() # here you tell your thread to stop 
      # it will stop the next time it passes at (checking if done)