python线程怎么销毁
答案:1 悬赏:40 手机版
解决时间 2021-04-14 06:00
- 提问者网友:缘字诀
- 2021-04-13 15:38
python线程怎么销毁
最佳答案
- 五星知识达人网友:英雄的欲望
- 2021-04-13 16:06
可以新建一个线程作为父线程,然后实际工作是在它的一个子线程里面做,父线程循环检测一个变量来决定是否退出。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()
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯