Python lock, Semaphore, event implements thread synchronization

Source: Internet
Author: User
Tags semaphore

Lock mechanism Whether you are Java, C #, or Python are common thread synchronization mechanism, compared to the C # lock mechanism, Python locking is relatively simple, directly call the threading standard library lock can be. Python's lock class has two functions, namely the acquire function and the release function, which act as a lock, set the state to locked, the latter is unlocked, and the state is set to unlocked. Let's look at the code:

#python multi-threaded sync lockImportThreading fromTimeImportSleepnum=0lock=Threading. Lock ()deffunc (ST):GlobalNumPrint(Threading.currentthread (). GetName () +'try to acquire the lock')    ifLock.acquire ():#modify the state to locked        Print(Threading.currentthread (). GetName () +'acquire the lock.')        Print(Threading.currentthread (). GetName () +":%s"%str (num)) Num+ = 1#Sleep (ST)        Print(Threading.currentthread (). GetName () +'release the lock.') lock.release ()#Modify the state to unlockedT1= Threading. Thread (Target=func, args= (8,)) T2= Threading. Thread (Target=func, args= (4,)) T3= Threading. Thread (Target=func, args= (2,)) T1.start () T2.start () T3.start ( )

We open three threads to call the same Func function, because of the uncertainty of the thread, if there is no lock, then run the words will be very chaotic, three threads to execute the same function, if the variable is involved in the data change is a pit! So we've added locks to ensure the correctness of the data and the order of the function execution!

Semaphore semaphore mechanism in Python is also very simple to implement thread synchronization. If you have a certain understanding of the operating system, then the operating system's PV primitive operation should be an impression, the semaphore is based on this mechanism. The semaphore class is a class under the threading module, the main two functions: Acquire function, release function, and lock The function of the class is the same, but the function is not the same, the parameters of the acquire function of the semaphore mechanism allow you to set the maximum concurrency, that is, how many threads are allowed to operate the same function or variable, and the execution is decremented once, and the release function is incremented. If the count is 0, the thread is blocked and the thread is no longer allowed access to the method or variable.

#python multi-threaded synchronization semaphoreImportThreading#Initialize Semaphore quantity ... When the call acquire the number to 0, the blocking thread waits for other threads to call the release () functionSemaphore = Threading. Semaphore (2)deffunc ():ifSemaphore.acquire (): forIinchRange (5):            Print(Threading.currentthread (). GetName () +'Get Semaphore') semaphore.release ()Print(Threading.currentthread (). GetName () +'release Semaphore')if __name__=='__main__':     forIinchRange (4): T1= Threading. Thread (target=func) T1.start ()

We allow two threads at a time to execute functions simultaneously, which can be seen from:

The event mechanism can not only realize the communication between threads, but also is a good way to realize thread synchronization. Events are one of the simplest mechanisms for communication between threads, and a thread indicates that an event and other threads are waiting for it.
Event.py is a class under the threading module that compares the previous two mechanisms, which provides four methods, namely the Is_set () function, the set () function, the clear () function, and the wait () function.
Is_set determines whether the event management flag is not true, only true when it returns
Set sets the flag to True
Clear sets the flag to Flase
Wait waits until the flag is true to stop blocking threads

ImportLoggingImportThreadingImport Time#print thread name and log informationLogging.basicconfig (level=logging. DEBUG, format="(% (threadname) -10s:% (message) s", )defwait_for_event_timeout (E, T):"""Wait t seconds and then timeout"""     while  notE.isset (): Logging.debug ("Wait_for_event_timeout Starting") Event_is_set= e.wait (t)#blocking, waiting set to TrueLogging.debug ("Event set:%s"%event_is_set)ifEvent_is_set:logging.debug ("Processing Event")        Else: Logging.debug ("doing other work") e= Threading. Event ()#Initialize to FalseT2 = Threading. Thread (name="Nonblock", Target=wait_for_event_timeout, args= (E, 2) ) T2.start () Logging.debug ("waiting before calling Event.set ()")#Time.sleep (7)E.set ()#wakes the thread while setting the event to TrueLogging.debug ("Event is set")

Python lock, Semaphore, event implements thread synchronization

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.