Python的线程10 使用Event保证多线程同时执行 模

「这是我参与11月更文挑战的第27天,活动详情查看:2021最后一次更文挑战

正式的Python专栏第48篇,同学站住,别错过这个从0开始的文章!

前面分享了threading.Event类,它维持了一个信号(True/False)状态。

像田径跑道上蹲在起点的运动员,不分先后,同时听到枪响就开跑,用这个类来做很适合。

模拟:发出一声枪响

当然不是真的有枪响,而且代码调用Event类的对象实例的set函数。

因为Event类的函数是线程安全的,所以我们可以把运动员看成一个一个的线程,并排在跑道起点

所以这个思路代码就有了

1
2
3
4
5
python复制代码for _ in range(n):
def run():
wait for event ready
run
threading.Thread(target=run).start()

稍微写好一点,代码最终如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
python复制代码#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/27 10:43 下午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷学委
# @XueWeiTag: CodingDemo
# @File : thread_event.py
# @Project : hello
import threading
import time

xuewei_event = threading.Event()

print("event:", xuewei_event)
print("is_set:", xuewei_event.is_set())


def run():
print(" %s ready" % threading.current_thread().name)
xuewei_event.wait()
print(" %s go" % threading.current_thread().name)
time.sleep(0.5)
print(" %s completed" % threading.current_thread().name)


threads = []
for i in range(4):
t_name = "t-" + str(i)
t = threading.Thread(name=t_name, target=run)
threads.append(t)
t.start()

# 学委提示:赛场鸣枪,运动员开跑
for i in [3, 2, 1]:
print("学委倒数 count %s" % i)
time.sleep(1)
xuewei_event.set()
print("is_set:", xuewei_event.is_set())

for t in threads:
t.join()

这是运行结果:

屏幕快照 2021-11-29 下午10.55.07.png

多线程还有点意思

看看上面的代码,学委还模拟了3/2/1倒数,再开枪。

如图所示,多个线程都听到这个枪响不约而同的喊出了‘go’,最后不同时间达到终点了。

编程还是挺好玩的。 喜欢Python的朋友,请关注学委的 Python基础专栏 or Python入门到精通大专栏

持续学习持续开发,我是雷学委!

编程很有趣,关键是把技术搞透彻讲明白。

欢迎关注微信,点赞支持收藏!

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%