python thread怎么强制结束一个已开启核对进城

Python019

python thread怎么强制结束一个已开启核对进城,第1张

置子线程为守护线程,(setdaemon=True),当主线结束时,守护线程会自动结束。

_mport threading

?

_ef run(x):

?while x:

?print(x)

?

_ = threading.Thread(target=run,args=(4,), daemon=True)

?#t.setdaemon(True)

?#t.daemon=True

_.start() # 开始线程

?# t.join() # join() 表示主线程阻塞,一直等子线程执行结束

等待串口数据导致线程自己sleep而没有机会执行,主线程的join没法继续,方法就是这样的,换成这个能执行

from threading import *import time class MyThread(Thread):def run (self):self.ifdo = True while self.ifdo:print 'I am running...'time.sleep(0.1) def stop (self):print 'I will stop it...'self.ifdo = False tr = MyThread()tr.setDaemon(True)tr.start()time.sleep(1)tr.stop()tr.join()

这样就更直观了

from threading import *import time class MyThread(Thread):def run (self):self.ifdo = True while self.ifdo:print 'I am running...'time.sleep(2) def stop (self):print 'I am stopping it...'self.ifdo = False tr = MyThread()tr.setDaemon(True)tr.start()print 'I will stop it...'time.sleep(5)tr.stop()tr.join()