python关闭线程daemon_python中threading开启关闭线程操作

42bd13c6670274f0993c5c92419dc87e.png

在python中启动和关闭线程:

首先导入threading

import threading

然后定义一个方法

def serial_read():

...

...

然后定义线程,target指向要执行的方法

myThread = threading.Thread(target=serial_read)

启动它

myThread.start()

二、停止线程

不多说了直接上代码

import inspect

import ctypes

def _async_raise(tid, exctype):

"""raises the exception, performs cleanup if needed"""

tid = ctypes.c_long(tid)

if not inspect.isclass(exctype):

exctype = type(exctype)

res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))

if res == 0:

raise ValueError("invalid thread id")

elif res != 1:

# """if it returns a number greater than one, you"re in trouble,

# and you should call it again with exc=NULL to revert the effect"""

ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)

raise SystemError("PyThreadState_SetAsyncExc failed")

def stop_thread(thread):

_async_raise(thread.ident, SystemExit)

停止线程

stop_thread(myThread)

补充知识:python threading实现Thread的修改值,开始,运行,停止,并获得内部值

下面的半模版代码在 win7+python3.63 运行通过并且实测可行,为了广大想要实现python的多线程停止的同学

import threading

import time

class MyThread(threading.Thread):

def __init__(self):

threading.Thread.__init__(self)

self.Flag=True #停止标志位

self.Parm=0 #用来被外部访问的

#自行添加参数

def run(self):

while(True):

if(not self.Flag):

break

else:

time.sleep(2)

def setFlag(self,parm): #外部停止线程的操作函数

self.Flag=parm #boolean

def setParm(self,parm): #外部修改内部信息函数

self.Parm=parm

def getParm(self): #外部获得内部信息函数

return self.Parm

if __name__=="__main__":

testThread=MyThread()

testThread.setDaemon(True) #设为保护线程,主进程结束会关闭线程

testThread.getParm() #获得线程内部值

testThread.setParm(1) #修改线程内部值

testThread.start() #开始线程

print(testThread.getParm()) #输出内部信息

time.sleep(2) #主进程休眠 2 秒

testThread.setFlag(False) #修改线程运行状态

time.sleep(2) #2019.04.25 修改

print(testThread.is_alive()) #查看线程运行状态

于2018-08-24修正一次,修正为在继承thread.Thread时,没有对父类初始化

旧:

def __init__(self):

self.Flag=True #停止标志位

self.Parm=0 #用来被外部访问的

#自行添加参数

新:

def __init__(self):

threading.Thread.__init__(self)

self.Flag=True #停止标志位

self.Parm=0 #用来被外部访问的

#自行添加参数

于2019年4月25日进行第二次修正,发现设置flag值后仍为true输出的情况,原因是输出在修改完成前执行,睡眠后结果正常

以上这篇python中threading开启关闭线程操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持云海天教程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Python,可以使用threading模块来创建和管理线程。要关闭一个线程,可以使用Thread对象的方法之一——setDaemon()。将线程daemon标志设置为True,可以将线程设置为守护线程,这意味着当主线程退出时,它将自动关闭。例如: ``` import threading import time def worker(): print("Starting worker thread") time.sleep(5) print("Exiting worker thread") t = threading.Thread(target=worker) t.setDaemon(True) # 将线程设置为守护线程 t.start() print("Main thread exiting") ``` 在上面的示例,worker线程被设置为守护线程,因此当主线程退出时,它将自动关闭。如果不将线程设置为守护线程,则必须手动关闭线程,例如: ``` import threading import time def worker(): print("Starting worker thread") time.sleep(5) print("Exiting worker thread") t = threading.Thread(target=worker) t.start() time.sleep(2) # 等待2秒钟 t._stop() # 关闭线程 print("Main thread exiting") ``` 在上面的示例,worker线程将在5秒钟后退出。但是,我们在等待2秒钟后手动关闭线程。请注意,这种方法不是很安全,因为它可能会导致线程在执行某些操作时被强制终止。因此,最好使用setDaemon()方法来关闭线程。 ### 回答2: 在Python关闭线程的方式主要有两种:通过设置标志位或使用线程对象的方法。 第一种方式是通过设置标志位来控制线程结束。在需要结束线程时,可以通过设置一个变量或标志位来通知线程退出循环,达到结束线程的目的。例如: ```python import threading import time class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.stop_event = threading.Event() def run(self): while not self.stop_event.is_set(): print("Thread is running...") time.sleep(1) def stop(self): self.stop_event.set() t = MyThread() t.start() time.sleep(5) t.stop() ``` 在上面的代码,我们通过一个名为 stop_event 的 threading.Event() 对象来控制线程是否退出循环。在 run() 方法,我们使用了 is_set() 方法检查标志位是否被设置为 True,如果是,则退出循环并结束线程。 第二种方式是使用线程对象的方法来结束线程Python线程对象提供了一个 stop() 方法用于结束线程。但是,由于这个方法在Python2被废弃,在Python3也已经不存在了。因此,我们需要自己实现一个 stop() 方法来结束线程一个简单的例子如下: ```python import threading import time class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.running = True def run(self): while self.running: print("Thread is running...") time.sleep(1) def stop(self): self.running = False t = MyThread() t.start() time.sleep(5) t.stop() ``` 在上面的代码,我们通过设置一个 boolean 类型的变量 running 来控制线程是否结束。在 stop() 方法,我们将 running 设置为 False,从而结束线程的运行。需要注意的是,不推荐使用这种方法来结束线程,因为它可能会导致线程在执行关键代码时被意外打断,从而导致程序出错或崩溃。 ### 回答3: Python线程Thread)是一种轻量级的执行流,它可以让程序同时执行多个任务,从而提高程序的效率。线程的启动和关闭Python线程编程的核心问题。其关闭线程是一种常见的需求,因为有时候我们需要手动结束一个线程,例如:线程执行的任务已经完成,或者线程的执行出现了错误,我们希望手动结束它。 Python线程关闭方式与启动方式类似,可以使用线程对象的stop()方法或者将一个状态变量设置为False来结束一个线程。 使用 stop() 方法结束线程: 1. 在线程函数,使用一个无限循环,不断地执行线程任务。 2. 在一个外部线程,调用要结束的线程对象的 stop() 方法。 3. stop() 方法会使得线程的执行结束,但是一般并不建议使用这种方式来结束线程,因为它会导致程序的不可预测性和安全性。 使用状态变量结束线程: 1. 在线程函数,使用一个 while 循环,循环条件为状态变量为 True。 2. 在一个外部线程修改状态变量为 False,从而使得线程终止循环,退出线程。 下面是一个使用状态变量结束线程的示例代码: ```python import threading import time class MyThread(threading.Thread): def __init__(self, threadID, name): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.isStop = False def run(self): while self.isStop == False: print("%s is running" % self.name) time.sleep(1) print("%s is stopped" % self.name) def stop(self): self.isStop = True if __name__ == "__main__": t1 = MyThread(1, "Thread-1") t2 = MyThread(2, "Thread-2") t1.start() t2.start() time.sleep(10) t1.stop() t2.stop() ``` 以上代码,MyThread 类继承自 threading.Thread 类,并且重载了 run() 方法,使用一个无限循环来执行线程任务。同时,MyThread 类还定义了一个状态变量 isStop,用于控制线程的退出。在主线程,先启动了两个 MyThread 类对象 t1 和 t2,然后等待 10 秒后,调用 t1.stop() 和 t2.stop() 方法,将状态变量设置为 False,从而使得线程停止循环,退出线程。 总结来说,在 Python 线程关闭并非一定要用 stop() 方法,因为 stop() 方法并不能保证线程的安全性和可预测性。使用一个状态变量来控制线程退出是一种更好的方式,可以让程序更加可靠和安全。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值