2016-04-06 5 views
5

मुझे यह कोड मिला है, मैं func1 से func2 कैसे रोक सकता हूं? Thread(target = func1).stop() की तरह कुछ काम नहीं करता हैथ्रेड पाइथन

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() 

उत्तर

0

यह बेहतर करने के लिए , को रोकने के लिए अपने अन्य धागा पूछना उदाहरण के लिए एक संदेश कतार का उपयोग कर रहा है।

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

में वापसी करना है लेकिन जब मैं उदाहरण के लिए चाहते हैं func1 के अंत में raw_input का उपयोग करें। फिर func2 func1 को बंद नहीं कर सकता है। क्या इसका कोई समाधान है? –

0

आप एक धागा बंद करने के लिए नहीं बता सकते हैं, आप इसे अपने लक्ष्य समारोह

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) 
संबंधित मुद्दे