Linux thread synchronization-conditional variables

Source: Internet
Author: User

 

1. Related functions
# Include <pthread. h>
Pthread_cond_t cond = pthread_cond_initializer;
Int pthread_cond_init (pthread_cond_t * cond, pthread_condattr_t
* Cond_attr );
Int pthread_cond_signal (pthread_cond_t * Cond );
Int pthread_cond_broadcast (pthread_cond_t * Cond );
Int pthread_cond_wait (pthread_cond_t * cond, pthread_mutex_t * mutex );
Int pthread_cond_timedwait (pthread_cond_t * cond, pthread_mutex_t
* Mutex, const struct timespec * abstime );
Int pthread_cond_destroy (pthread_cond_t * Cond );

2. Description
Conditional variables are a synchronization mechanism that allows threads to be suspended until certain conditions on shared data are met. Basic operations on condition variables include: trigger conditions (when the condition changes to true); waiting conditions, suspending the thread until other threads trigger conditions.
A condition variable must be associated with the mutex to avoid conditional competition. A thread is waiting for a condition variable. When it is waiting for the variable, another thread triggers the condition.
Pthread_cond_init uses the attribute specified by cond_attr to initialize the condition variable cond. When cond_attr is null, the default attribute is used. The threads implementation condition variable does not support attributes, so the cond_attr parameter is ignored.
Variables of the pthread_cond_t type can also be statically initialized using the pthread_cond_initializer constant.
Pthread_cond_signal enables a thread in the thread waiting on the condition variable to start again. If there is no waiting thread, nothing will be done. If multiple threads are waiting for this condition, only one thread can be restarted, but no one can be specified.
Pthread_cond_broadcast restarts all threads waiting for the condition variable. If there is no waiting thread, nothing will be done.
Pthread_cond_wait automatically unlocks the mutex (like executing pthread_unlock_mutex) and waits for the conditional variable to be triggered. At this time, the thread hangs and does not occupy the CPU time until the condition variable is triggered. Before calling pthread_cond_wait, the application must lock the mutex. The pthread_cond_wait function automatically locks the mutex (like executing pthread_lock_mutex) before returning it ).
The unlock of mutex and suspension of conditional variables are automatically performed. Therefore, before a condition variable is triggered, if all threads need to lock the mutex, this mechanism can ensure that the thread locks the mutex and enters the waiting condition variable, condition variables are not triggered.
Like pthread_cond_timedwait and pthread_cond_wait, pthread_cond_wait automatically unlocks mutex and waiting condition variables, but it also limits the waiting time. If cond is not triggered within the time specified by abstime, mutex is re-locked and pthread_cond_timedwait returns the error etimedout. The abstime parameter specifies an absolute time. The time origin is the same as time and gettimeofday: abstime = 0 indicates 00:00:00 GMT on January 1, January 1, 1970.
Pthread_cond_destroy destroys a condition variable and releases its resources. Before entering pthread_cond_destroy, there must be no threads waiting on the condition variable. In the implementation of linuxthreads, condition variables do not join resources. Besides checking whether there are any waiting threads, pthread_cond_destroy actually does nothing.
3. Cancel
Pthread_cond_wait and pthread_cond_timedwait are cancellation points. If a thread is canceled when it is suspended on these functions, the thread continues to execute immediately, and then locks pthread_cond_wait and pthread_cond_timedwait In the mutex parameter again, and finally cancels the execution. Therefore, when you call the clear handler, make sure that mutex is locked.
4. async-signal safety)
Conditional Variable functions are not asynchronous signal security and should not be called in the signal processing program. Note that calling the pthread_cond_signal or pthread_cond_boardcast function in the signal processing program may cause a deadlock in the calling thread.

5. Return Value
When the execution is successful, all the Conditional Variable Functions return 0, and the non-zero error code is returned.
6. Error Code
Pthread_cond_init, pthread_cond_signal, pthread_cond_broadcast, and pthread_cond_wait never return error codes.
When an error occurs in the pthread_cond_timedwait function, the following error code is returned:
When the time specified by etimedout abstime times out, the condition variable is not triggered
Eintr pthread_cond_timedwait is triggered to interrupt
When an error occurs in the pthread_cond_destroy function, the following error code is returned:
Ebusy some threads are waiting for this condition variable
7. Example
There are two shared variables X and Y, which are protected by mut muts. When x> Y, the condition variable cond is triggered.
Int X, Y;
Int X, Y;
Pthread_mutex_t mut = pthread_mutex_initializer;
Pthread_cond_t cond = pthread_cond_initializer;

Wait until the execution process of x> Y is:
Pthread_mutex_lock (& MUT );
While (x <= y ){
Pthread_cond_wait (& cond, & MUT );
}
/* Perform operations on x and y */
Pthread_mutex_unlock (& MUT );

Modification to X and Y may result in x> Y. The condition variable should be triggered:
Pthread_mutex_lock (& MUT );
/* Modify x and y */
If (x> Y) pthread_cond_broadcast (& Cond );
Pthread_mutex_unlock (& MUT );

If it can be determined that at most one waiting thread needs to be awakened (for example, if only two threads communicate through X and Y), pthread_cond_signal is slightly more efficient than pthread_cond_broadcast. If not, use pthread_cond_broadcast.
Wait for x> Y in 5 seconds:

Struct timeval now;
Struct timespec timeout;
Int retcode;

Pthread_mutex_lock (& MUT );
Gettimeofday (& now );
Timeout. TV _sec = now. TV _sec + 5;
Timeout. TV _nsec = now. TV _usec * 1000;
Retcode = 0;
While (x <= Y & retcode! = Etimedout ){
Retcode = pthread_cond_timedwait (& cond, & Mut, & timeout );
}
If (retcode = etimedout ){
/* Timeout */
} Else {
/* Operate x and y */
}
Pthread_mutex_unlock (& MUT );

 

 

 Original article addressHttp://blog.csdn.net/hiflower/archive/2008/03/18/2195350.aspx

 

 

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.