Thread synchronization (Mutex and semaphore function and difference)

Source: Internet
Author: User
Tags mutex posix semaphore

"The semaphore is synchronized with multi-threaded multitasking, and one thread completes an action by telling the other thread that the other thread is going to do some action (where everyone is blocking when they are semtake)." The mutex is used in multi-threaded multitasking, a thread occupies a resource, then the other threads can not access, until the thread unlock, other threads can start to use this resource. For example, access to global variables, sometimes to add locks, the operation is over, in the unlock. Sometimes locks and semaphores are used at the same time.
In other words, the semaphore is not necessarily locking a resource, but the concept of the process, such as: There are a,b two threads, b thread to wait for a thread to complete a task after the next step of their own, the task is not necessarily locked a resource, but also to do some calculation or data processing and so on. The thread mutex is the concept of "lock a resource", and other threads cannot manipulate the protected data during the lock period. In some cases the two can be interchanged.

The difference between the two:

Scope
Semaphore: Process/Line Cheng (unknown semaphore between Linux threads pthread semaphore)
Mutual exclusion Locks: between threads

When locked
Semaphore: As long as the value of the semaphore is greater than 0, the other thread can sem_wait success, after the success of the signal value minus one. If the value is not greater than 0, the sem_wait causes the thread to block until the value is added to the Sem_post release, but before the sem_wait returns, the value value is reduced by one
Mutex: No other thread can access the protected resource as long as it is locked

Here are some of the concepts of Semaphore (volume):

The main difference between a semaphore and a mutex and a condition variable lies in the concept of "light", which means that resources are available and lights are not. If the latter two synchronized mode focuses on the "wait" operation, that is, resources are not available, the signal mechanism is focused on lighting, that is, to inform the availability of resources;
There is no point in waiting for the thread to unlock or excite the condition, and the light operation of the thread without waiting for the light is valid and can keep the lights on. Of course, such an operating primitive also means more overhead.

The application of signal lights in addition to light/light out of this binary lamp, can also be more than 1 of the number of lights to indicate that the number of resources is greater than 1, at this time can be called multiple lights.

1. Create and Log off

POSIX signal standard defines the name of the signal and the unknown signal lights, but the realization of the linuxthreads only nameless lights, at the same time the famous lamp can always be used in addition to the many processes, in the use of the nameless lights and not very different, so the following only on the nameless lights for discussion.

int Sem_init (sem_t *sem, int pshared, unsigned int value)
This is the API for creating the semaphore, where value is the initial value of the semaphore, and pshared represents whether it is shared for multiple processes and not just for a process. Linuxthreads does not implement a multiple-process shared semaphore, so all pshared inputs that are not 0-valued will return Sem_init () to 1, and the errno to Enosys. The initialized signal lamp is characterized by SEM variable, and is used for the following operation of lighting and quenching.

int Sem_destroy (SEM_T * sem)
The cancellation of the signal light SEM requires no thread to wait for the signal, or return-1, and set errno as Ebusy. In addition, the Linuxthreads Semaphore logoff function does not do other actions.
Sem_destroy destroys a semaphore object, freeing the resources it might hold. No threads should is waiting on the
Semaphore at the time Sem_destroy is called. In the Linuxthreads implementation, No. are associated with
Semaphore objects, thus Sem_destroy actually does nothing except ' no thread is checking on the waiting.

2. Lighting and lights

int sem_post (SEM_T * sem)

The lighting operation adds 1 to the semaphore value, indicating an additional accessible resource.

int sem_wait (SEM_T * sem)
int sem_trywait (SEM_T * sem)

Sem_wait () waits for the light operation, waits for the light to light (the semaphore value is greater than 0), and then the signal atom is reduced by 1, and returns. Sem_trywait () is a non-blocking version of Sem_wait (), if the semaphore count is greater than 0, then the atom is reduced by 1 and returns 0, otherwise the -1,errno is immediately returned to Eagain.

3. Get Light value

int Sem_getvalue (SEM_T * sem, int * sval)

Read the light count in the SEM, save in the *sval, and return 0.

4. Other

Sem_wait () is implemented as a cancellation point. What do you mean, cancel something? )
Sem_wait is a cancellation point.
The meaning of the cancellation point:
When using Pthread_cancel () a thread, the requirement is pending and the thread is actually removed when the cancel thread goes to the next cancellation point.
And in the architecture that supports atomic "compare and Exchange CAs" directives, sem_post () is the only one that can be used for asynchronous signal processing functions for POSIX asynchronous signal security APIs.

On processors supporting atomic compare-and-swap (Intel 486, Pentium and later, Alpha, PowerPC, MIPS II, Motorola 68k),
The Sem_post function is async-signal safe and can therefore to called from signal handlers. This are the only thread syn-
Chronization function provided by POSIX threads, is async-signal safe.

On the Intel 386 and the Sparc, the current linuxthreads implementation of Sem_post isn't async-signal safe by lack of
The required atomic operations.

Mutex (mutex)

The data structure of mutual exclusion is also treated as a two-yuan semaphore. A mutex is essentially a multitasking-sensitive two-dollar signal that can be used as a synchronous multitasking behavior that is often used to protect the critical segment code from interrupts and to use resources in a shared synchronization.

A mutex is essentially a lock that provides exclusive access to resources, so the main role of a mutex is to be mutually exclusive. The value of the mutex object, with only 0 and 12 values. These two values represent the two states of a mutex, respectively. A value of 0 indicates a lock state, the current object is locked, and the user process/thread enters the queue if it tries to lock the critical resource, the value is 1, 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 to four actions:

-Create created

-Lock Lock

-Unlock Unlock

-Destruction of Destroy

When a mutex is created, it can have an initial value 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 lock to the mutex (the system typically returns immediately on the second call). In other words, locking and unlocking these two corresponding operations need to be done in the same thread.

Mutex functions provided in different operating systems:

Action \ System

Win32

Linyx

Solaris

Create

CreateMutex

Pthread_mutex_init

Mutex_init

Lock

WaitForSingleObject

Pthread_mutex_lock

Mutex_lock

Unlock

ReleaseMutex

Pthread_mutex_unlock

Mutex_unlock

Destroyed

CloseHandle

Pthread_mutex_destroy

Mutex_destroy

Signal Volume

Semaphores (semaphore), sometimes referred to as semaphores, are a facility used in multi-threaded environments that coordinate threads to ensure that they can use public resources correctly and rationally.

The semaphore can be divided into several categories:

² binary semaphore (binary semaphore): only allow the semaphore to take 0 or 1 values, which can only be obtained by one thread at a time.

² integer semaphore (integer semaphore): The semaphore value is an integer that can be obtained at the same time by multiple threads until the value of the semaphore changes to 0.

² recorded semaphore (record semaphore): Each semaphore S has a list of waiting queues in addition to an integer value (count), which is the identity of each thread that is blocking the semaphore. When the semaphore is released, a value is added, the system automatically wakes up a waiting thread from the waiting queue, allowing it to get the semaphore, while the semaphore is reduced by one.

Semaphores control access to shared resources through a single counter, and the value of the semaphore is a non-negative integer, and all threads passing through it subtract the whole number. If the counter is greater than 0, access is allowed, the counter is reduced by 1, and if 0, access is blocked, and all threads attempting to pass it will be in a waiting state.

The result of a 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 semaphore count is greater than 0, the thread obtains a pass, which causes the count of the semaphore to decrement, otherwise the thread will block until a pass is obtained. When this thread no longer needs to access the shared resource, it releases the pass, which causes the count of semaphores to increase, and if another thread waits for the pass, that thread will get a pass at that time.

Semaphore can be abstracted to five operations:

-Create created

-Waiting for wait:

The thread waits for the semaphore, if the value is greater than 0, then gets, the value minus one; if only equals 0, a straight path goes to sleep, knowing that the semaphore value is greater than 0 or timed out.

-Release Post

Executes a release semaphore, the value plus one, and wakes the thread if there is a waiting thread at this time.

-Trying to wait for trywait

If the call trywait, the thread does not really get the semaphore, or check whether the semaphore can be obtained, if the semaphore value is greater than 0, then the trywait return success, otherwise the return failed.

-Destruction of Destroy

semaphores, which can be used to protect two or more critical pieces of code that cannot be invoked concurrently. Before entering a critical code segment, the thread must obtain a semaphore. 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 this critical code segment 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 on the first end of each critical code segment, respectively. Confirm that these semaphore VI refer to the initial semaphore created.

Action \ System

Win32

Posix

Create

CreateSemaphore

Sem_init

Wait

WaitForSingleObject

SEM _wait

Release

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.