Linux Thread Management

Source: Internet
Author: User

Parsing 1

In a Linux environment, multithreaded programming is bound to encounter situations where conditional variables are required, and the pthread_cond_wait () function must be used at this time. But the execution of this function is more difficult to understand.
The workflow for Pthread_cond_wait () is as follows (in the case of example in man):
Consider variables x and y, protected by the mutex Mut,and a condition vari-
Able cond that's to be signaled whenever X becomes greater thany.

int x, y;
pthread_mutex_t mut = Pthread_mutex_initializer;
pthread_cond_t cond = Pthread_cond_initializer;

Waiting until X is greater than Y is performed asfollows:

Pthread_mutex_lock (&mut);
while (x <= y) {
Pthread_cond_wait (&cond,&mut);
}

Pthread_mutex_unlock (&mut);

Modifications on x and y so cause X to become greater than yshould signal the con-
dition if needed:

Pthread_mutex_lock (&mut);

if (x > Y) pthread_cond_broadcast (&cond);
Pthread_mutex_unlock (&mut);

This example means that two threads are going to modify the values of x and Y, the first thread hangs when x<=y, and continues execution until x>y (the second thread may modify the value of x, Y, and when X>y wakes the first thread), That is, first initialize a common mutex mut and a conditional variable cond. The following function bodies are then executed separately in two threads:

Pthread_mutex_lock (&mut);
while (x <= y) {
Pthread_cond_wait (&cond,&mut);
}

Pthread_mutex_unlock (&mut);while function: because there may be multiple threads waiting,Pthread_cond_wait returns, if the A thread will get mut first, when the other threads become blocked, if a modifies x, y so that x<=y other threads do not need to execute, so add while judgment.

And:        pthread_mutex_lock (&mut);
             
              if (x > Y) pthread_cond_signal (&cond);
             pthread_mutex_unlock (& Mut)  
    the execution of a function is very simple, when the first thread executes to pthread_cond_wait (&cond,&mut), at this point, if x<=y, This function unlocks the Mut mutex  , and then locks the cond condition variable  , at which point the first thread hangs   (no CPU cycles are consumed).
    in the second thread, it would have been blocked because Mut was locked by the first thread, because Mut has been freed, so the lock mut can be obtained, and the values of x and Y are modified, and after the modification, an if statement determines whether the x>y, If it is, then the pthread_cond_signal () function wakes the first thread  , and releases the mutex mut in the next sentence. Then the first thread starts executing from pthread_cond_wait (), first to lock Mut again   If the lock succeeds, then the condition is judged   (As for why use while, that is, after being awakened, there is a reason for analysis), if the condition is met, is woken   processed, and the mutex mut  is finally released.

As for why the conditional judgment (i.e. why the while loop is used to judge the condition) after being awakened is because there may be a "surprise group effect". Some people think that since it is awakened, must be satisfied with the conditions, it is not. If multiple threads are waiting for this condition and only one thread can handle it at the same time, the condition must be judged again so that only one thread enters the critical section. For this, turn to a paragraph:

Refer to the following POSIX rationale:

Condition Wait semantics

It is important to note this when pthread_cond_wait () andpthread_cond_timedwait () return without error, the associatedpred Icate may still is false. Similarly, whenpthread_cond_timedwait () returns with the timeout error, theassociated predicate is true due to an unav Oidable Race betweenthe expiration of the timeout and the predicate statechange.

The application needs to recheck the predicate on all returnbecause it cannot be sure there are another thread waiting on t Hethread to handle the signal, and if there are not then the signal islost. The burden is on the application to check thepredicate.

Some implementations, particularly on a multi-processor, maysometimes cause multiple threads to wake up when the condition Variable is signaled simultaneously on differentprocessors.

In general, whenever a condition wait returns, the thread had tore-evaluate the predicate associated with the condition WA It todetermine whether it can safely proceed, should wait again, orshould declare a timeout. A return from the wait does not implythat the associated predicate is either true orfalse.

It is the thus recommended that a condition wait being enclosed in theequivalent of a ' while loop ' that checks thepredicate.

As can be seen from the above:
1,pthread_cond_signal can wake up multiple threads at the same time on multiple processors, and when you have only one thread to handle a task, the other wake-up threads need to continue wait,while the meaning of the loop is here, and the specification requires Pthread_cond_ Signal wakes up at least one thread on a pthread_cond_wait, but some implementations can also wake up multiple threads on a single processor in order to be simple.
2, some applications, such as the thread pool, Pthread_cond_broadcast wake up all threads, but we usually only need a subset of the threads to perform the task, so other threads need to continue wait. It is highly recommended to use the while loop here.

In fact, it is simple to say that pthread_cond_signal () can also wake up multiple threads, and if you only allow one thread to access it, you must use while to make conditional judgments to ensure that only one thread in the critical section is processing.

Parsing 2

2. Thread synchronization using conditional variables (recommended)

The use of blocking and messaging methods can greatly reduce the waste of resources and increase the real-time

Thread condition Variable pthread_cond_t

Thread waits for a condition

int pthread_cond_timedwait (pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex,const struct Timespec * Restrict abstime);

int pthread_cond_wait (pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex);

Notification functions

to notify all threads

int Pthread_cond_broadcast (pthread_cond_t *cond);

Only a single thread is notified

int pthread_cond_signal (pthread_cond_t *cond);

---------------------------------------------------------------------------------

The right way to use


pthread_cond_wait Usage:

Pthread_mutex_lock (&mutex);

while (Condition_is_false)

{

Pthread_cond_wait (&cond,&mutex);

}

Condition_is_false=true; This operation is locked, which means that only one thread enters the block at the same time.

Pthread_mutex_unlock (&mutex);

----------------------------------------------------


Pthread_cond_signal usage:

Pthread_mutex_lock (&mutex);

Condition_is_false=false;

Pthread_cond_signal (&cond)

Pthread_mutex_unlock (&mutex)

--------------------------------------------------------

Remember the above usage!!! Can avoid misuse of pthread_cond_broadcast and release all condition variables

Reference http://blog.csdn.net/mashang123456789/article/details/9792677

Linux Thread Management

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.