擅长:python、mysql、java
<p>不能告诉线程停止,必须使其在目标函数中返回</p>
<pre><code>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)
</code></pre>