停止线程Python

停止线程Python,python,multithreading,Python,Multithreading,我有这个代码,我怎样才能从func1阻止func2?类似于线程(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__': Th

我有这个代码,我怎样才能从func1阻止func2?类似于
线程(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()
最好让其他线程停止,例如使用消息队列

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

你不能告诉线程停止,你必须让它在目标函数中返回

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)

但是当我想在func1的末尾使用raw_输入时。那么func2无法关闭func1。有什么解决办法吗?