11.python Concurrency Primer (part5 event object)

Source: Internet
Author: User
Tags redis server

First, the introduction of the event.

Each thread is a self-running individual, and the running state of each thread is unpredictable.

If there are many threads in a program, other threads of the program need to determine the running state of a thread to decide what to do next.

The event object in the threading module happens to do this, and the event object contains a signal flag bit that can be set through the thread, which allows the thread to wait for certain events to occur.

In the case of initialization, the signal ID in the event object is set to False, and if a thread waits for the event object, and the event object's signal is "false", then the thread will be blocked until the event signal is marked "true", All threads waiting on this event object will be awakened.

That is, if a thread waits for the signal flag in the event object to be "true", the thread ignores the event and continues execution.


Second, the event object common methods.

Event.isset (): Returns the status value of the event.

Event.wait (): When the signal ID inside the event object is set to False (false), all threads waiting for the event object will all be blocked.


Event.set (): Sets the signal inside the event object to be "true" (true), and all threads waiting for the event object will be woken up waiting for the operating system to dispatch.


Event.clear (): The status value of recovery event is false.


The following diagram will give you a clear understanding of the relationship between Event.wait and Event.set:

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/877318/201705/877318-20170505171348945-1408243578. PNG "width=" 381 "height=" 381 "/>


Third, the event uses an example.

Let's consider the application scenario for the event object.

If, in a program, multiple threads need to go to Redis to fetch data, each thread tries to connect to the Redis server, and in general, if the connection is unsuccessful, Redis will need to try to reconnect on all threads.

If we want to make sure that the Redis server is working properly when the program starts, and then the other working threads connect to the Redis server, using the event object is a good choice when it comes to this requirement.

We can use the event mechanism to allow each working thread to do a simple communication, the main thread to connect to the Redis server, if connected to the event object, the signal identity is changed 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) s ',)

Def worker (event):

Logging.debug ("Waiting for Redis ready ....")

Event.wait ()

Logging.debug ("Redis Ready,and connect to Redis server and does 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 was 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 was OK, and then trigger the Redis ready event

(threading-1) Redis Ready,and Connect to Redis server and does some work Sun 14 09:35:46 2017

(threading-2) Redis Ready,and Connect to Redis server and does some work Sun 14 09:35:46 2017


Code Analysis:

In the above code, altogether opened three threads, respectively is threading-1 and Threading-2 also has the main thread, first the main thread runs the main () function, has produced an event object, this event object signal initial value is false, Then threading-1 and threading-2 two threads were created and run, output a log first of All,check Redis server, make sure it was OK, and then trigger the Redi S ready event after sleep 3 seconds, this time switch to Threading-1,threading-1 first executes the worker function, outputs a log, Then execute the Event.wait method, when the event object's signal is identified as false, Threading-1 is blocked, temporarily unable to execute the Woker function after the content, when the threading-1 is blocked, then switch to threading-2 (why must switch to T Where's hreading-2? This is because the main thread is still in sleep), threading-2 at this time also to execute the Woker function, the same first output a log waiting for the 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, starts to run down, executes the redis_ready.set (), the signal flag in the event object named Redis_ready that we created becomes true, When the signal flag of this event object becomes true, the previously blocked threading-1 and threading-2 are awakened, continuing with the code behind the Woker function.

(threading-1) Redis Ready,and Connect to Redis server and does some work Sun 14 09:35:46 2017

(threading-2) Redis Ready,and Connect to Redis server and does some work Sun 14 09:35:46 2017


Iv. additions to the event object.

Threading. The wait method of the event also accepts a timeout parameter, by default, if the event does not occur consistently, the wait method blocks until the timeout parameter is added, and if the blocking time exceeds the value set by this parameter, the Wait method returns. Corresponding to the above scenario, if the Redis server does not start consistently, we want the child threads to be able to print some logs to constantly remind us that there is currently no Redis service to connect to, and we can set this timeout parameter to achieve this goal:


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 does some work [%s] ', Time.ctime ())

Time.sleep (1)


This article is from the "Rebirth" blog, make sure to keep this source http://suhaozhi.blog.51cto.com/7272298/1925428

11.python Concurrency Starter (part5 event object)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.