“This is the 27th day of my participation in the Gwen Challenge in November. See details of the event: The Last Gwen Challenge in 2021”
Official Python column # 48, stop! Don’t miss this zero-based article!
The threading.Event class was shared earlier, which maintains a signal (True/False) state.
Like the athletes squatting at the starting point of the track and field, regardless of sequence, at the same time heard the gun started to run, with this class to do very suitable.
Simulation: A shot is fired
Of course, there is no actual gunshot, and the code calls the set function of an object instance of the Event class.
Because the Event class functions are thread-safe, we can treat the runners as threads, side by side, at the start of the track.
So there you have it
for _ in range(n):
def run() :
wait for event ready
run
threading.Thread(target=run).start()
Copy the code
To do a little better, the code ends up like this:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @time: 2021/11/27 10:43 PM
# @Author : LeiXueWei
# @csDN /Juejin/Wechat: Lei Xuewei
# @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()
Tip: Shots are fired and athletes start running
for i in [3.2.1] :print("学委倒数 count %s" % i)
time.sleep(1)
xuewei_event.set(a)print("is_set:", xuewei_event.is_set())
for t in threads:
t.join()
Copy the code
Here is the result:
Multithreading is kind of interesting
Look at the code above. The committee also simulates 3/2/1 countdown before firing.
As shown in the figure, multiple threads hear the shot and say ‘go’ at the same time, and finally reach the finish line at different times.
Programming is fun. For those who like Python, please check out the Python Basics section or the Python Getting Started to Master Section
Continuous learning and continuous development, I am Lei Xuewei! Programming is fun. The key is to get the technology right. Welcome to wechat, like support collection!