Semaphore semaphores and semaphore signals
I. Preface
The mutex lock allows only one thread to change data at the same time, while Semaphore allows a certain number of threads to change data at the same time. For example, if there are three pits in the toilet, only three persons can go to the toilet at most, the people later can only wait for someone to come in.
Ii. semaphore
Semaphore is a variable that controls access to public resources or critical zones. Semaphores maintain a counter, specifying the number of threads that can simultaneously access resources or enter the critical section. Every time a thread obtains a semaphore, counter-1. If the counter is 0, other threads stop the access semaphore until the other thread releases the semaphore. Each time acquire () is called, the built-in counter-1 + 1 is called every time release () is called.
#-*-Coding: UTF-8-*-import threadingimport timeclass MyThread (threading. thread): def run (self): global num semaphore. acquire () # obtain the signal lock. acquire () num + = 1 print ('run the thread: % s \ n' % self. name) print ('Now the number is ', num) lock. release () time. sleep (1) semaphore. release () # release signal lock num = 0 lock = threading. lock () # Up to five threads can run semaphore = threading at the same time. boundedSemaphore (5) if _ name _ = '_ main _ _ ': For I in range (17): t = MyThread () t. start () while threading. active_count ()! = 1: pass else: print ('-- all threads done ---') print (num)
Note:
- The program runs in five groups. In fact, if a thread completes and releases the semaphore, the waiting thread can obtain the semaphore, but no more than five.
- When multiple threads run at the same time, there will still be thread security issues, so we need to lock the competition for shared resources.
Iii. application scenarios