Conditional variables in LINUX multi-thread programming

Source: Internet
Author: User
Document directory
  • Index:
Condition variable (condition variable)

It is also a device used for synchronization. It allows a process (or thread) to suspend itself and wait for the state of a conditional variable to be changed.
There are several functions:

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 );

I want to see the names to know their purpose. Usually we also use static variables to initialize a conditional variable.
Example:
Pthread_cond_t cond = pthread_cond_initializer;

Pthread_cond_signal is used to wake up a locked thread.
Pthread_cond_broadcast is used to wake up all locked threads.
Pthread_cond_wait is used to wait.

To solve the competition problem (that is, a thread is just going to wait and another thread is already signal), it must be used with a mutex.

Take a look at the following typical example. Assume that the variables X and Y are shared by multiple threads. We hope this thread will continue to run until X and Y are equal. The typical busy waiting method is as follows (this is an incorrect method ):

while( x != y );

 

The following are the correct methods for using conditional variables:


Pthread_mutex_t mut = pthread_mutex_initializer;
Pthread_cond_t cond = pthread_cond_initializer;

// Waiting until X is the same as Y is saved med as follows:

Pthread_mutex_lock (& MUT );
While (X! = Y ){
Pthread_cond_wait (& cond, & MUT );
}
/** // * Operate on x and y */
Pthread_mutex_unlock (& MUT );

The execution process of pthread_cond_wait is as follows:
1. First, it unlocks the mutex and then suspends the current thread.
2. When it is awakened, it will lock the mutex.

This ensures that this is a critical section.

PS: Reproduced: http://www.duangw.net/computer/history/pthread/condition.html
Conditional Variable index:
  1. Initialize the condition variable pthread_cond_init.
  2. Blocking on the condition variable pthread_cond_wait
  3. Unblocking pthread_cond_signal on condition Variables
  4. Blocking until the specified time pthread_cond_timedwait
  5. Release all blocked threads pthread_cond_broadcast
  6. Release condition variable pthread_cond_destroy
  7. Wakeup loss problems
1. initialize the condition variable pthread_cond_init
# Include <pthread. h>
Int pthread_cond_init (pthread_cond_t * CV,
Const pthread_condattr_t * cattr );
Returned value: 0 is returned if the function is successful. Any other returned values indicate an error.

Initialize a condition variable. When the cattr parameter is a null pointer, the function creates a default conditional variable. Otherwise, the attribute of the condition variable is determined by the attribute value in cattr. When calling the pthread_cond_init function, the NULL pointer of the cattr parameter is equivalent to the default attribute in cattr, but the former does not need the memory overhead occupied by cattr. When this function returns, the condition variable is stored in the memory pointed to by the parameter cv.

You can use the macro pthread_cond_initializer to initialize the statically defined conditional variables so that they have default attributes. This is the same as the dynamic allocation using the pthread_cond_init function. No error check is performed during initialization. For example:

pthread_cond_t cv = PTHREAD_COND_INITIALIZER;

A condition variable cannot be initialized by multiple threads at the same time. When a conditional variable needs to be reinitialized or released, the application must ensure that the conditional variable is not used.

 

2. Block pthread_cond_wait on the condition variable
# Include <pthread. h>
Int pthread_cond_wait (pthread_cond_t * CV,
Pthread_mutex_t * mutex );
Returned value: 0 is returned if the function is successful. Any other returned values indicate an error.

The function will unlock the mutex lock pointed to by the mutex parameter and block the current thread on the condition variable pointed to by the CV parameter.

The blocked thread can be awakened by the pthread_cond_signal function, pthread_cond_broadcast function, or after the signal is interrupted.

The return of the pthread_cond_wait function does not mean that the condition value has changed. You must re-check the condition value.

When the pthread_cond_wait function returns, the corresponding mutex lock will be locked by the current thread, even if a function error is returned.

Generally, a condition expression is checked under the protection of a mutex lock. When the condition expression is not met, the thread will still block the condition variable. When another thread changes the condition value and sends a signal to the condition variable, wait for one or all threads on the condition variable to be awakened, then they attempt to occupy the corresponding mutex again.

After the thread on the condition variable is awakened, the value of the condition may change until the pthread_cond_wait () function returns. Therefore, after the function is returned, the condition value must be re-tested before the corresponding mutex lock is locked. The best test method is to call the pthread_cond_wait function cyclically and set the expressions that meet the condition to the termination condition of the loop. For example:

pthread_mutex_lock();
while (condition_is_false)
pthread_cond_wait();
pthread_mutex_unlock();

The order in which different threads blocked on the same condition variable are released is not certain.

Note: The pthread_cond_wait () function is the exit point. If a pending exit request exists when this function is called, and the thread can exit, this thread will be terminated and start executing the aftercare function, and the mutex lock related to the condition variable will remain locked.

 

3. Remove the blocking pthread_cond_signal on the condition variable.
# Include <pthread. h>
Int pthread_cond_signal (pthread_cond_t * cv );
Returned value: 0 is returned if the function is successful. Any other returned values indicate an error.

A function is used to release a thread that is blocked on a specified condition variable.

The corresponding conditional variables must be used under the protection of mutex. Otherwise, the unlock of the condition variable may occur before the condition variable is locked, resulting in a deadlock.

The sequence of all threads in the wake-up blocking condition variable is determined by the scheduling policy. If the thread scheduling policy is sched_other type, the system will wake up the thread based on the priority of the thread.

If no thread is blocked on the condition variable, calling pthread_cond_signal () will not work.

 

4. Blocking until the specified time pthread_cond_timedwait
# Include <pthread. h>
# Include <time. h>
Int pthread_cond_timedwait (pthread_cond_t * CV,
Pthread_mutex_t * MP, const structtimespec * abstime );
Returned value: 0 is returned if the function is successful. Any other returned values indicate an error.

When the function reaches a certain period of time, the blocking will be lifted even if the condition does not occur. This time is specified by the parameter abstime. When a function is returned, the corresponding mutex lock is often locked, even if a function error is returned.

Note: The pthread_cond_timedwait function also exits.

The timeout parameter is a time in a day. Example:

pthread_timestruc_t to;
to.tv_sec = time(NULL) + TIMEOUT;
to.tv_nsec = 0;

The error code returned for timeout is etimedout.

 

5. Release all blocked threads pthread_cond_broadcast
# Include <pthread. h>
Int pthread_cond_broadcast (pthread_cond_t * cv );
Returned value: 0 is returned if the function is successful. Any other returned values indicate an error.

The function wakes up all threads blocked by the pthread_cond_wait function on a condition variable. The CV parameter is used to specify this condition variable. When no thread is blocked on this condition variable, the pthread_cond_broadcast function is invalid.

Because the pthread_cond_broadcast function wakes up all threads that are blocked on a condition variable, these threads will compete for the corresponding mutex lock again after being awakened, so you must use the pthread_cond_broadcast function with caution.

 

6. Release the condition variable pthread_cond_destroy.
# Include <pthread. h>
Int pthread_cond_destroy (pthread_cond_t * cv );
Returned value: 0 is returned if the function is successful. Any other returned values indicate an error.

Release the condition variable.

Note: the space occupied by the condition variable is not released.

 

7. Wakeup loss problems

Calling the pthread_cond_signal or pthread_cond_broadcast function may cause the loss of wake-up when the thread does not obtain the corresponding mutex lock.

Wake-up loss often occurs in the following situations:

  1. One thread calls the pthread_cond_signal or pthread_cond_broadcast function;
  2. The other thread is located between the test condition variable and the call of the pthread_cond_wait function;
  3. No thread is in a blocked wait state.

From: http://blog.chinaunix.net/u/16292/showart_1820604.html

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.