Thread synchronization (the role and difference between mutex and semaphore)

Source: Internet
Author: User
Tags posix semaphore

"Semaphores are used in multi-threaded multitasking, where one thread completes an action by telling another thread about the semaphore, and the other thread is doing some action (where everyone is blocking when they are semtake). 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 locks and semaphores are used simultaneously "in other words, the semaphore is not necessarily locking a resource, but the concept of the process, such as: There is a A, a, two threads, b thread to wait for a thread to complete a task after the next step, this task does not necessarily lock a resource, It can also be some sort of calculation or data processing. The 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 difference between the two:Scope Signal Volume: Process or line threads (unknown semaphore between Linux threads only pthread semaphore)Mutual exclusion Lock: Between Threadssignal Volume when locked:As long as the semaphore value is greater than 0, the other thread can sem_wait success, and the value of the semaphore is reduced by one after success. If value is not greater than 0, then sem_wait causes the thread to block until Sem_post is released with a value of one, but the value is reduced by one until Sem_wait returns.Mutual exclusion Lock:No other thread can access the protected resource as long as it is locked. The following are some concepts of Semaphore (volume): The main difference between a semaphore and a mutex and a condition variable is the concept of "light", which means that the resource is available and the light off means it is unavailable. If the latter two-way focus on the "wait" operation, that is, the resource is not available, the beacon mechanism is focused on lighting, that is, to inform the resource is available, there is no waiting for the thread to unlock or excitation conditions are meaningless, and not waiting for the light to light the lighting operation is valid, and can keep the light state. Of course, such an operation primitive also means more overhead. The application of signal lights except the light/lamp out of this binary lamp, you can also use more than 1 lamp number, to indicate that the number of resources greater than 1, this can be called multi-lamp. 1. Creating and unregistering POSIX semaphore standards defines both the famous and nameless lights, but the implementation of Linuxthreads only has the nameless lamp, while the famous lamps are always used in addition to the multi-process, in the use with the nameless lamp is not very different, so the following is only the nameless lights discussed. intSem_init (sem_t *sem,intpshared, unsignedintvalue) This is the API that creates the semaphore, where value is the initial value of the semaphore, and pshared indicates whether it is a multi-process share and not just for a process. Linuxthreads does not implement a multi-process shared semaphore, so all pshared inputs that are not 0 values will cause sem_init () to return-1, and the errno is Enosys. The well-initialized signals are characterized by SEM variables and are used for the following illumination and lamp operation. intSem_destroy (sem_t *SEM) The sign-off of the semaphore SEM requires that no thread is waiting for the semaphore, otherwise it returns-1, and the errno is ebusy. In addition, Linuxthreads's semaphore logoff function does not perform other actions. Sem_destroy destroys a semaphoreObject, freeing the resources it might hold. No threads should be waiting on the semaphore at the time Sem_destroy iscalled. In the Linuxthreads implementation, no resources is associated with semaphore objects, thus Sem_destroy actually Does nothing except checking that no thread iswaiting on the semaphore.2. Lighting and extinguishing lightsintSem_post (sem_t *sem) lighting operation adds 1 to the beacon value, indicating an additional accessible resource. intSem_wait (sem_t *sem)intSem_trywait (sem_t *SEM) sem_wait () waits for the light to light up, waits for the light to light (the semaphore value is greater than 0), and then the signal is atomically reduced by 1 and returned. Sem_trywait () is a non-blocking version of Sem_wait (), and if the semaphore count is greater than 0, the atom is reduced by 1 and returns 0, otherwise returns immediately-1, and the errno is placed as Eagain. 3. Get Lamp valueintSem_getvalue (sem_t * sem,int*sval) Read the lamp count in the SEM, stored in*Sval, and returns 0. 4. Other sem_wait () are implemented as cancellation points. (What do you mean by canceling something??? ) sem_wait  is A cancellation point. The meaning of cancellation points: When using Pthread_cancel () a thread, this requirement is pending up, and when the canceled thread goes to the next cancellation point, The thread will be really cancel out. and, on the architecture that supports the atomic "Compare and exchange CAS" Directive, sem_post () is the only API that can be used to secure POSIX asynchronous signals for asynchronous signal processing functions. On processors supporting atomic compare-and-swap (Intel486, Pentium and later, Alpha, PowerPC, MIPS II, Motorola 68k), the Sem_post function is Async-signal safe and can therefore be called fromSignal handlers. This isThe only thread syn-chronization function provided by POSIX threads that is Async-signal safe. on the Intel386And the Sparc, the current linuxthreads implementation of Sem_post isNotAsync-signal safe by lack of the required atomic operations. Mutex (mutex) mutex is a data structure that shows mutual exclusion and is also considered as a two-yuan semaphore. A mutex is basically a multitasking-sensitive two-dollar signal that can be used as a synchronous multitasking behavior, and it is commonly used as a resource to protect critical segment code from interrupts and to use it in shared synchronization. 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 an attempt is made to lock a critical resource, a value of 1 indicates an idle state, the current object is idle, the user process/the thread can lock the critical resource, and then the mutex value minus 1 becomes 0. A mutex can be abstracted into four operations:-Creating Create-Locking Lock-Unlock Unlock-destroying Destroymutex can have an initial value when created, indicating whether the mutex is locked or idle after it is created. In the same thread, in order to prevent deadlocks, the system does not allow two consecutive times to locking the mutex (the system typically returns immediately on the second call). That is, the two corresponding operations, lock and unlock, need to be done in the same thread. Mutex functions available in different operating systems: Semaphore Semaphore (Semaphore), sometimes referred to as 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. Semaphores can be divided into several categories: ² binary semaphore (binary semaphore): Only the semaphore is allowed to take 0 or 1 values, which can only be obtained by one thread. ² integer semaphore (integer semaphore): The semaphore value is an integer that can be obtained simultaneously by multiple threads until the value of the semaphore becomes 0. ² recorded semaphore (record semaphore): Each semaphore s In addition to an integer value (count), there is a wait queue list, which is the identity of each thread that is blocking the semaphore. When the semaphore is released one, and the value is added one after another, the system automatically wakes up a waiting thread from the waiting queue, letting it get the semaphore, and the semaphore minus one more. The semaphore Controls access to the shared resource through a counter, and the value of the semaphore is a nonnegative integer, and all threads that pass it will subtract that integer by one. If the counter is greater than 0, access is allowed, the counter is reduced by 1, and if it is 0, access is forbidden and all threads trying to pass through it will be in a wait state. The result of the counter calculation is a pass that allows access to shared resources. Therefore, in order to access the shared resource, the thread must obtain a pass from the semaphore, and if the count of that semaphore is greater than 0, then this thread obtains a pass, which causes the count of semaphores to decrement, otherwise the thread will block until a pass is obtained. When this thread no longer needs access to the shared resource, it frees the pass, which causes the semaphore count to increment, and if another thread waits for a pass, then that thread will get the pass at that time. Semaphore can be abstracted as five operations:-Creating Create-wait waiting: The thread waits for the semaphore, if the value is greater than 0, the value is obtained, minus one, and if it equals 0, a straight line goes to sleep, knowing that the semaphore value is greater than 0 or time out. -releases the post execution to release the semaphore, the value is added one, and if there is a waiting thread at this time, the thread is awakened. -trying to wait for trywait if the trywait is called, the thread does not really get the semaphore, or checks whether the semaphore can be obtained, or if the semaphore value is greater than 0, the trywait returns successfully, otherwise the return fails. -destroying the destroy semaphore can be used to protect two or more critical sections of code that cannot be called concurrently. The thread must obtain a semaphore before entering a critical code segment. If there are no threads in the critical code snippet, the thread immediately enters that part of the block diagram. Once the critical code fragment is complete, the thread must release the semaphore. Other threads that want to enter the critical snippet must wait until the first thread releases the semaphore. To complete this process, you need to create a semaphore and then place the acquire Semaphore VI and release Semaphore VI respectively at the first end of each critical code segment. Confirm that the Semaphore VI refers to the initial created semaphore. The difference between the mutex and the semaphore1. 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. 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. Synchronization: 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 time2. The mutex value can only be 0/1, the semaphore value can be a non-negative integer. 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. 3. 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.
Http://www.blogjava.net/fhtdy2004/archive/2009/07/05/285519.html

Thread synchronization (the role and difference between mutex and 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.