Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Getting started with 11.python concurrency (part5 event object)

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

First, introduce event.

Each thread is an individual running independently, and the running state of each thread is unpredictable.

If there are many threads in a program, other threads in the program need to judge the running status of a thread to determine what they are going to do next.

The event object in the threading module does just that, and the event object contains a beacon bit that can be set by the thread, which allows the thread to wait for certain events to occur.

By default, the signal flag in the event object is set to "false". If a thread is waiting for the event object and the event object's signal is marked as "false", the thread will be blocked until the event signal is marked "true" and all threads waiting for the event object will be awakened.

That is, if a thread waits for the "true" flag bit in the event object, the thread ignores the event (event) and continues to execute.

Second, the common methods of event object.

Event.isSet (): returns the status value of event.

Event.wait (): when the signal flag inside the event object is set to "False", all threads waiting for the event object will be blocked.

Event.set (): sets the signal inside the event object to be marked as "True", and all threads waiting for this event object will be awakened to wait for scheduling by the operating system.

Event.clear (): the status value for restoring event is False.

The following diagram gives you a clear understanding of the relationship between event.wait and event.set:

Third, the use of event examples.

Let's consider the application scenario of event objects.

If, in a program, there are multiple threads that need to go to the redis to get data, and each thread has to try to connect to the redis server, in general, if the redis connection is not successful, all threads need to try to reconnect.

If we want to make sure that the redis server works properly when the program starts, and then let other working threads connect to the redis server, using the event object is a very good choice when faced with this requirement.

We can use the event mechanism to let each working thread to do a simple communication, the main thread to connect to the redis server, if connected, the signal identification in the event object changes to true, the rest of the working thread will be awakened.

Example:

#! / usr/local/bin/python2.7

#-*-coding:utf-8-*-

Import threading

Import time

Import logging

Logging.basicConfig (level=logging.DEBUG, format=' (% (threadName)-10s)% (message) slots,)

Def worker (event):

Logging.debug ("waiting for redis ready....")

Event.wait ()

Logging.debug ("redis ready,and connect to redis server and do some work% s", time.ctime ())

Time.sleep (1)

Def main ():

Redis_ready = threading.Event ()

T1 = threading.Thread (target=worker,args= (redis_ready,), name= "threading-1")

T1.start ()

T2 = threading.Thread (target=worker,args= (redis_ready,), name= "threading-2")

T2.start ()

Logging.debug ("first of all,check redis server, make sure it is ok, and then trigger the redis ready event")

Time.sleep (3)

Redis_ready.set ()

If _ _ name__ = ='_ _ main__':

Main ()

Output result:

(threading-1) waiting for redis ready....

(threading-2) waiting for redis ready....

(MainThread) first of all,check redis server, make sure it is ok, and then trigger the redis ready event

(threading-1) redis ready,and connect to redis server and do some work Sun May 14 09:35:46 2017

(threading-2) redis ready,and connect to redis server and do some work Sun May 14 09:35:46 2017

Code analysis:

In the above code, a total of three threads are opened, namely threading-1 and threading-2, and the main thread. First, the main thread runs the main () function, which produces an event object. The initial value of the event object signal is False, and then two threads, threading-1 and threading-2, are created and run. Sleep 3 seconds after outputting a log first of all,check redis server, make sure it is ok, and and then trigger the redis ready event. When you switch to threading-1,threading-1, you first execute the worker function, output the log once, and then execute the event.wait method. When the signal of the event object is identified as False, threading-1 is blocked, and the content behind the woker function cannot be executed temporarily. When threading-1 is blocked, then switch to threading-2 (why do you have to switch to threading-2? This is because the main thread is still in sleep), and threading-2 also executes the woker function at this time, and also outputs a log waiting for redis ready....,. When executed to event.wait, the signal flag bit of this event object is still False, so when it is executed here, threading-2 will also be blocked.

After 3 seconds, the MainThread main thread sleep ends and starts to run downwards. After executing redis_ready.set (), the signal flag in the event object named redis_ready that we created will become True. When the signal flag of the event object becomes True, both the previously blocked threading-1 and threading-2 will be awakened and continue to execute the code behind the woker function.

(threading-1) redis ready,and connect to redis server and do some work Sun May 14 09:35:46 2017

(threading-2) redis ready,and connect to redis server and do some work Sun May 14 09:35:46 2017

Fourth, the supplement of event object.

Threading.Event 's wait method also accepts a timeout parameter. By default, if the event does not occur, the wait method will block all the time, and after adding this timeout parameter, if the blocking time exceeds the value set by this parameter, the wait method will return. Corresponding to the above application scenario, if the Redis server is not started, we hope that the child thread can print some logs to constantly remind us that there is no Redis service to which we can connect. We can achieve this goal by setting this timeout parameter:

Def worker (event):

While not event.is_set ():

Logging.debug ('Waiting for redis ready...')

Event.wait (2)

Logging.debug ('redis ready, and connect to redis server and do some work [% s]', time.ctime ())

Time.sleep (1)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report