粗鲁的将一个线程关闭是不可取的,因为该线程可能正在访问一些需要主动关闭的资源或者该线程还产生了另外一些需要关闭的线程。因此Python threading并没有提供线程关闭的API。
为了程序的需要,我们可能确实需要主动关闭一些线程,有两种方法可以work around:
- 一种是用python multiprocessing的多进程来代替多线程,multiprocessing提供了关闭进程的接口terminate。
import time
from processing import Process
class test():
def f(self, name):
ctr = 0
while 1:
ctr += 1
print ' hello', name, ctr
time.sleep(0.5)
if __name__ == '__main__':
CT=test()
p = Process(target=CT.f, args=('P',))
p.start()
key = raw_input("Press ")
p.terminate() ## p2 terminated here
|
import threading
import time
class TestThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.running = True
self.times = 0
def run(self):
#note: we don't set self.running to False anywhere...
while self.running:
self.times += 1
print self.times
time.sleep(.05)
if __name__ == '__main__':
# create the thread
thread = TestThread()
# start it up
thread.start()
raw_input("Hit ")
# don't continue the while loop anymore
thread.running = False
# wait for the thread to finish what it's doing
thread.join()
|
阅读(3537) | 评论(0) | 转发(0) |