Why does a mutex need to be used in conjunction with a conditional variable

Source: Internet
Author: User
Tags mutex
The mutex embodies a kind of competition, I leave, inform you to come in.
Cond embodies a kind of collaboration, I am ready to inform you to start.
One obvious disadvantage of a mutex is that it has only two states: locked and unlocked. The condition variable, which compensates for the lack of a mutex by allowing the thread to block and wait for another thread to send the signal, is often used in conjunction with the mutex. When used, a condition variable is used to block a thread, and when the condition is not satisfied, the thread often unlocks the corresponding mutex and waits for the condition to change. Once another thread changes the condition variable, he notifies the corresponding condition variable to wake one or more threads that are being blocked by this condition variable. These threads will lock the mutex again and test the condition for satisfaction. In general, conditional variables are used to synchronize between threads.
When two threads operate the same critical section, through mutual exclusion lock protection, if a thread has been locked, b thread will be blocked when the lock, until a release lock, B to obtain the lock operation, process B must be constantly active access to locks, check conditions, release locks, and then get the lock, check, and then release, It is only possible (while other threads in this process have been waiting for the end of the thread) to meet the conditions in which they are running, compared to consuming the resources of the system. And the condition variable is also blocked, also need to notify to wake up, after the thread is awakened, it will check to determine whether the condition is satisfied, if not satisfied, the thread is dormant, should still be blocked here, waiting for the condition to be awakened after the meeting, saving the thread running waste of resources. This process is generally implemented with a while statement. When thread B discovers that the locked variable does not meet the condition, it automatically releases the lock and puts itself in a waiting state, giving the CPU control over to the other threads. Other threads have the opportunity to do so at this point, and then notify the thread that is trapped in the waiting state because the condition is not satisfied when the modification is complete. This is a notification model synchronization mode, greatly saving CPU computing resources, reducing the competition between the threads, but also improve the efficiency of the system between the threads. This type of synchronization is the condition variable.
The above description may be a bit abstract, considering the simple scenario: a pseudo code description.
A thread takes elements from the queue, and B threads stores the elements in the queue. No lock-free implementation is considered. A mutex is needed to protect the consistency of queues, and two threads are prevented from simultaneously manipulating the queue to destroy the data structure.
When the queue is empty, a requires constant probing of the queue status:
while (1)
{
If (queue is empty)
Hibernate 10s
Else
{
Lock
Take element
Unlock
}
}
There is a problem with the possibility that B puts the element when it is just entering hibernation, but still needs to hibernate the full 10s time. Cause unnecessary delay. Of course, if you do not sleep, you can, but it will cause unnecessary CPU overhead. You can avoid these problems by using event notification wakeup mechanisms based on conditional variables.
Once B executes pthread_cond_signal () when the element is finished, the currently blocked thread is immediately awakened and begins to work.
while (1) {
Pthread_mutex_lock ();
Pthread_cond_wait ();
take element;
Pthread_mutex_unlock ();
}


Conditional variables are protected with mutexes, and conditional variable state changes should lock the mutex first, and pthread_cond_wait () needs to pass in a locked mutex that joins the calling thread into the invocation list of the waiting condition and then releases the mutex. When the condition is satisfied and leaves the pthread_cond_wait (), the mutex is locked back, and the two functions are atomic operations. You can eliminate the time gap between the condition occurrence and the thread sleep wait condition. Other threads do not perceive this change until they obtain a mutex, because the mutex must be locked to calculate the condition. All in all, in order to avoid the angered or miscalculation resulting from a condition that determines the gap between a statement and a subsequent body or wait statement, a mutex is used to guarantee that any relevant operation, including (judging, modifying) of a cond, is accessed by only one thread at a time. In other words, the condition variable itself is a competitive resource, the function of which is the execution of the body of the subsequent program, and a lock is used to protect it. This closes the time channel between the condition check and the thread entering the hibernation wait condition to change the two operations so that there is no change in the thread.
The feeling can be summed up as follows: The condition variable is used for a thread to protect the critical section that it will operate when certain conditions are established, which prevents the thread from constantly polling to check if the condition is set up to reduce the efficiency, which is the efficiency improvement ... When the condition is satisfied, automatically exits the block, and then adds the lock to carry on the operation.
The above is about efficiency, in addition the mutex also has a disadvantage is that it will cause deadlock.
For example, thread A and thread B require exclusive use of 2 resources, but they all occupy one resource and then wait for the release of another resource, which creates a deadlock.
The conditional variable acts as a blocking and wake-up thread, so the mutex is usually matched to the conditional variable.
    To solve these problems, conditional variables are often used in conjunction with mutexes, and condition variables compensate for the lack of mutexes by allowing threads to block and wait for another thread to send a signal. When used, a condition variable is used to block a thread, and when the condition is not satisfied, the thread often unlocks the corresponding mutex and waits for the condition to change. Once another thread changes the condition variable, it notifies the corresponding condition variable to wake one or more threads that are being blocked by this condition variable. These threads will lock the mutex again and test the condition for satisfaction.

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.