1 Star 0 Fork 231

疾风/python-learn

forked from mktime/python-learn 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
howto_terminate_thread.py 924 Bytes
一键复制 编辑 原始数据 按行查看 历史
内部项目 提交于 2021-09-13 16:32 . 如何优雅退出线程
from threading import Thread
import time
import threading
global_flag = {}
CRITICAL_THREAD_EXIT = 20
def log(msg):
timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
thread_name = threading.current_thread().getName()
print('[' + timestamp + '][' + thread_name + ']' + msg + '\n')
def do_deal():
while True:
global_flag.setdefault(threading.current_thread().name, 0)
global_flag[threading.current_thread().name] += 1
log('current_flag:' + str(global_flag[threading.current_thread().name]))
if global_flag[threading.current_thread().name] > CRITICAL_THREAD_EXIT:
# stop thread
print('task queue is empty, and triggered quit signal, bye!')
break
else:
print("task queue is empty, sleep a while.")
time.sleep(1)
continue
Thread(target=do_deal, name='producer1').start()
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/JFXX/python-learn.git
git@gitee.com:JFXX/python-learn.git
JFXX
python-learn
python-learn
master

搜索帮助