python 中如何退出线程
大家好,我正在用 python 编写套接字编程并使用多线程,但是当我想退出程序时遇到一个问题,似乎我无法退出正在运行的线程。
def create_workers():
for _ in range(NUMBER_OF_THREADS):
t = threading.Thread(target=work)
t.daemon = True # End the Thread
t.start()
def work():
while True:
x = queue.get()
if x == 1:
create_socket()
bind_socket()
accept_connections()
if x == 2:
start_turtle()
break
queue.task_done()
函数create_workers正在运行两个线程并且目标函数工作,但我不这样做在函数工作中打破 while 循环后真的知道终止它
Hi guy I am writing a socket programming in python and using multithreading but I have one problem when I want to exit a program It seem like I can not exit a running thread.
def create_workers():
for _ in range(NUMBER_OF_THREADS):
t = threading.Thread(target=work)
t.daemon = True # End the Thread
t.start()
def work():
while True:
x = queue.get()
if x == 1:
create_socket()
bind_socket()
accept_connections()
if x == 2:
start_turtle()
break
queue.task_done()
the function create_workers are running two thread and targeting function work but I don't really know to terminate it after I break a while loop in function work
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
threading.Event
实例作为您在work
结束之前设置的标志,并检查它是否在无限循环的每次迭代开始时设置。如果您的
work
函数更复杂,有多个return
语句,您可以将event.set()
调用放入finally 中
块。try
语句的threading.Event
是线程安全的。正如user2357112 支持 Monica 所指出的,使线程成为守护进程没有意义,所以我删除了该行。
Use a
threading.Event
instance as a flag that you set just beforework
ends, and check if it is set at the start of each iteration of the infinite loop.If your
work
function is more complicated, with multiplereturn
statements, you could chuck theevent.set()
call into thefinally
block of atry
statement.threading.Event
is thread-safe.As pointed out by user2357112 supports Monica, making the threads daemonic doesn't make sense, so I've removed that line.
您可以使用
python-worker
(链接)you can use
python-worker
(link)