分离线程之后怎么等待线程执行完毕
时间: 2023-11-28 07:54:54 浏览: 80
在分离线程后,主线程无法直接等待子线程执行完毕,因为子线程已经与主线程分离。但是,可以使用以下方法等待子线程执行完毕:
1. 使用join()方法:在创建子线程时,将子线程对象保存在主线程中,然后在主线程中使用join()方法等待子线程执行完毕。
示例代码:
```python
import threading
def worker():
print("Sub thread start")
# do something
print("Sub thread end")
t = threading.Thread(target=worker)
t.setDaemon(True) # 设为分离线程
t.start()
# 主线程等待子线程执行完毕
t.join()
print("Main thread end")
```
2. 使用Event对象:在主线程中创建一个Event对象,然后将这个对象传递给子线程,在子线程中使用Event对象的wait()方法等待主线程的信号,主线程执行完毕后,调用Event对象的set()方法发出信号,通知子线程结束。
示例代码:
```python
import threading
def worker(event):
print("Sub thread start")
event.wait() # 等待主线程发出信号
print("Sub thread end")
event = threading.Event()
t = threading.Thread(target=worker, args=(event,))
t.setDaemon(True) # 设为分离线程
t.start()
# 主线程等待一段时间后发出信号
time.sleep(3)
event.set()
print("Main thread end")
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)