Semaphore semaphores and semaphore signals

Source: Internet
Author: User

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

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.