12, Seventh week-network programming-semaphores in Threads (Semaphore)

Source: Internet
Author: User
Tags mutex semaphore

  

mutexes allow only one thread to change data, while Semaphore allows a certain number of threads to change the data at the same time. The following is a brief introduction:

Semaphores are used in multi-threaded multitasking, where one thread completes an action to tell another thread through the semaphore, and the other threads perform some action. The mutex is used in multi-threaded multitasking mutex, one thread occupies a certain resource, then other threads will not be able to access it, until the thread unlock, other threads will start to take advantage of this resource. For example, the access to global variables, sometimes to lock, the operation is finished, in the unlock. Sometimes the locks and semaphores are used at the same time.
That is, the semaphore is not necessarily locked a certain resource, but the concept of the process, such as: There is a A, a, a two thread, B thread to wait for a thread to complete a task after the next step, the task does not necessarily lock a resource, but also to do some calculation or data processing and so on. A thread mutex is the concept of "lock a Resource", during which other threads cannot manipulate the protected data. In some cases the two are interchangeable.

The semaphore (Semaphore), sometimes called a semaphore, is a facility used in a multithreaded environment that coordinates individual threads to ensure that they are able to use public resources correctly and rationally.

    • Creating create
    • Wait:: The thread waits for the semaphore, if the value is greater than 0, the value is obtained, minus one, and if it is equal to 0, a straight line goes to sleep, knowing that the semaphore value is greater than 0 or times out.
    • Release Post: Performs a release semaphore, the value is added one, and if there is a waiting thread at this time, the thread is awakened.
    • Try to wait for trywait: If the trywait is called, the thread does not really get the semaphore, or whether the semaphore can be obtained, or if the semaphore value is greater than 0, the trywait returns successfully, otherwise the return fails.
    • Destroying Destroy

A mutex is essentially a lock that provides exclusive access to a resource, so the main purpose of the mutex is to use mutex. The value of a mutex object, with only 0 and 12 values. These two values also represent the two states of the mutex, respectively. A value of 0 indicates a locked state, the current object is locked, and the user process/thread enters a queued wait if it tries to lock a critical resource, a value of 1 indicates an idle state, the current object is idle, the user process/thread can lock the critical resource, and then the mutex value is reduced by 1 to 0.

A mutex can be abstracted into four operations:

    • Creating create
    • Locking Lock
    • Unlock Unlock
    • Destroying Destroy

The difference between mutexes and semaphores:

    • mutexes are used for mutual exclusion of threads, and semaphores are used for thread synchronization. This is the fundamental difference between the mutex and the semaphore, which is the difference between the mutex and the synchronization.
    1. Mutex: Refers to a resource that allows only one visitor to access it, with uniqueness and exclusion. However, mutual exclusion cannot limit the order in which visitors access resources, that is, access is unordered.
    2. Signal: Refers to the mutual exclusion of the basis (in most cases), through other mechanisms to achieve the visitor's orderly access to resources. In most cases, synchronization has been mutually exclusive, especially if all writes to the resource must be mutually exclusive. In rare cases, multiple visitors can be allowed to access resources at the same time
    • The mutex value can only be 0/1, and the semaphore value may be a non-negative integer.
    1. In other words, a mutex can only be used for mutually exclusive access to a resource, and it cannot implement multi-threaded mutex issues for multiple resources. The semaphore can realize multi-thread mutual exclusion and synchronization of multiple homogeneous resources. When the semaphore is a single-valued semaphore, it is also possible to complete a mutually exclusive access to a resource.
    • the lock and unlock of the mutex must be used by the same thread, and the semaphore can be freed by one of the threads, and the other thread will get it.
Example: There are three public telephone booths, and three people can call. When someone came to call, there was a wait. To wait for the inside of the people out after the (inside the person out of this action, the equivalent of the signal, tell the outside people, to you call), outside the talent can go in, the next operation.
Import Threading,timedef Run (n):    semaphore.acquire ()    time.sleep (1)    print ("Run the  thread:%s\n"% n)    semaphore.release () if __name__ = = "__main__":    semaphore = Threading. Boundedsemaphore (4) #最多允许4个线程同时运行 for    i in range:        t = Threading. Thread (target=run,args= (i,))        T.start () while Threading.active_count ()! = 1:    passelse:    print ("--all Thread done--") output: Run the  thread:0run the  thread:1run the  thread:2run the  thread:3 run  the Thread:4run the Thread:7run the Thread:5run the Thread:6 run the Thread:9run the Thread:8  -- All thread done--process finished with exit code 0
Note: Each time you execute 4 threads, wait until the previous execution completes, and then proceed to the next one. The last two left will be executed together. The entire execution process is unordered.

12, Seventh week-network programming-semaphores in Threads (Semaphore)

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.