python 多线程 setdaemon_python多线程之t.setDaemon(True) 和 t.join()

本文详细介绍了Python多线程中t.setDaemon(True)和t.join()的区别与用法。t.setDaemon(True)设置子线程为守护线程,程序结束时忽略守护线程;t.join()会阻塞主线程,等待子线程执行完成。正确使用t.join()应在启动所有线程后,在单独的循环中调用,以确保主线程阻塞的时长等于最长子线程的执行时间。
摘要由CSDN通过智能技术生成

0.目录

1.参考

2.结论

(1)通过 t.setDaemon(True) 将子线程设置为守护进程(默认False),主线程代码执行完毕后,python程序退出,无需理会守护子线程的状态。

(2) t.join() 用于阻塞主线程,可以想象成将某个子线程的执行过程插入(join)到主线程的时间线上,主线程的后续代码延后执行。注意和 t.start() 分开写在两个for循环中。

(3)第一个for循环同时启动了所有子线程,随后在第二个for循环中执行t.join() ,主线程实际被阻塞的总时长==其中执行时间最长的一个子线程。

3.验证过程

1.参考

C:\Program Files\Anaconda2\Lib\threading.py

defdaemon(self):"""A boolean value indicating whether this thread is a daemon thread (True) or not (False).

This must be set before start() is called, otherwise RuntimeError is

raised. Its initial value is inherited from the creating thread; the

main thread is not a daemon thread and therefore all threads created in

the main thread default to daemon = False.

The entire Python program exits when no alive non-daemon threads are

left."""

def join(self, timeout=None):"""Wait until the thread terminates.

This blocks the calling thread until the thread whose join() method is

called terminates -- either normally or through an unhandled exception

or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a

floating point number specifying a timeout for the operation in seconds

(or fractions thereof). As join() always returns None, you must call

isAlive() after join() to decide whether a timeout happened -- if the

thread is still alive, the join() call timed out.

When the timeout argument is not present or None, the operatio

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值