python停止线程
时间: 2023-10-19 12:33:15 浏览: 49
在Python中,有几种方法可以停止线程。一种常见的方法是使用状态变量来控制线程的循环体,当状态变量为False时,线程退出循环并停止运行。另一种方法是使用全局变量作为状态变量,在主线程中修改全局变量的值来控制线程的停止。还可以使用threading.Event对象作为信号来停止线程。以下是这些方法的示例代码:
方法一: 使用状态变量停止线程
```python
import threading
import time
class Job(threading.Thread):
def __init__(self, *args, **kwargs):
super(Job, self).__init__(*args, **kwargs)
self.__flag = threading.Event() # 用于暂停线程的标识
self.__flag.set() # 设置为True
self.__running = threading.Event() # 用于停止线程的标识
self.__running.set() # 将running设置为True
def run(self):
while self.__running.isSet():
self.__flag.wait() # 为True时立即返回, 为False时阻塞直到self.__flag为True后返回
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
time.sleep(1)
def pause(self):
self.__flag.clear() # 设置为False, 让线程阻塞
def resume(self):
self.__flag.set() # 设置为True, 让线程停止阻塞
def stop(self):
self.__flag.set() # 将线程从暂停状态恢复, 如何已经暂停的话
self.__running.clear() # 设置为False
a = Job()
a.start()
time.sleep(3)
a.pause()
time.sleep(3)
a.resume()
# time.sleep(2)
# a.stop()
```
方法二: 使用全局变量停止线程
```python
import threading
import time
stop_threads = False
def run():
while True:
print('thread running')
global stop_threads
if stop_threads:
break
stop_threads = False
t1 = threading.Thread(target=run)
t1.start()
time.sleep(1)
stop_threads = True
t1.join()
print('thread killed')
```
方法三: 使用threading.Event对象停止线程
```python
import threading
import time
def run():
while True:
print('thread running')
if stop_event.is_set():
break
stop_event = threading.Event()
stop_event.clear()
t1 = threading.Thread(target=run)
t1.start()
time.sleep(1)
stop_event.set()
t1.join()
print('thread killed')
```
这些方法可以根据具体的需求选择使用,根据需要来选择合适的方法来停止线程。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [Python中线程的使用(停止操作)](https://blog.csdn.net/leishupei/article/details/114640480)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [python多线程编程:如何优雅地关闭线程](https://blog.csdn.net/captain5339/article/details/128360804)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]