python线程怎么销毁
1个回答
展开全部
可以新建一个线程作为父线程,然后实际工作是在它的一个子线程里面做,父线程循环检测一个变量来决定是否退出。Talk is cheap
import threading
class TestThread(threading.Thread):
def __init__(self, thread_num=0, timeout=1.0):
super(TestThread, self).__init__()
self.thread_num = thread_num
self.stopped = False
self.timeout = timeout
def run(self):
def target_func():
inp = raw_input("Thread %d: " % self.thread_num)
print('Thread %s input %s' % (self.thread_num, inp))
subthread = threading.Thread(target=target_func, args=())
subthread.setDaemon(True)
subthread.start()
while not self.stopped:
subthread.join(self.timeout)
print('Thread stopped')
def stop(self):
self.stopped = True
def isStopped(self):
return self.stopped
thread = TestThread()
thread.start()
import time
print('Main thread Wainting')
time.sleep(2)
thread.stop()
thread.join()
import threading
class TestThread(threading.Thread):
def __init__(self, thread_num=0, timeout=1.0):
super(TestThread, self).__init__()
self.thread_num = thread_num
self.stopped = False
self.timeout = timeout
def run(self):
def target_func():
inp = raw_input("Thread %d: " % self.thread_num)
print('Thread %s input %s' % (self.thread_num, inp))
subthread = threading.Thread(target=target_func, args=())
subthread.setDaemon(True)
subthread.start()
while not self.stopped:
subthread.join(self.timeout)
print('Thread stopped')
def stop(self):
self.stopped = True
def isStopped(self):
return self.stopped
thread = TestThread()
thread.start()
import time
print('Main thread Wainting')
time.sleep(2)
thread.stop()
thread.join()
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询