Conditional variables for Linux Thread Synchronization

Source: Internet
Author: User

Different from mutex lock,Conditional variables are used for waiting, not locking. Conditional variables are used to automatically block a thread until a special situation occurs..Usually the condition variable and mutex lock are used at the same time.

Conditional variables allow us to sleep and wait for certain conditions to appear. A condition variable is a mechanism for synchronizing global variables shared by threads. It mainly includes two actions: one thread waits for the condition variable to be established and suspends; another thread sets "condition to true" (a signal indicating condition to true ).

Condition Detection is performed under the protection of mutex lock. If a condition is false, a thread automatically blocks and releases the mutex lock waiting for the State to change. If another thread changes the condition, it sends a signal to the associated condition variable, wakes up one or more threads waiting for it, obtains the mutex lock again, And reevaluates the condition. If the two processes share the read/write memory, the condition variable can be used to synchronize threads between the two processes.

Before using conditional variables, initialize them first. A condition variable such as pthread_cond_t my_condition = pthread_cond_initializer can be generated and initialized in a single statement (used for inter-process thread communication ). The pthread_cond_init function can be used for dynamic initialization.

Conditional variables are divided into two parts: Conditions and variables. the condition itself is protected by mutex. the thread must lock the mutex before changing the condition state. it uses global variables shared between threads for synchronization.

The related functions are as follows:

1 int pthread_cond_init (pthread_cond_t * cond, pthread_condattr_t * cond_attr );
2 int pthread_cond_wait (pthread_cond_t * cond, pthread_mutex_t * mutex );
3 int pthread_cond_timewait (pthread_cond_t * cond, pthread_mutex * mutex, const timespec * abstime );
4 int pthread_cond_destroy (pthread_cond_t * Cond );
5 Int pthread_cond_signal (pthread_cond_t * Cond );
6 int pthread_cond_broadcast (pthread_cond_t * Cond); // remove all threads from blocking Brief Description: (1) initialization. init () or pthread_cond_t cond = pthread_cond_initialier; Attribute Set to null (2) Wait for the condition to be true. pthread_wait, pthread_timewait.wait () release the lock, and block the waiting condition variable to set the waiting time for true timewait (). If the waiting time is not signal yet, etimeout is returned (only one thread is supported by the lock) (3) activation condition variable: pthread_cond_signal, pthread_cond_broadcast (activate all waiting threads) (4) clear condition variable: destroy; wireless process waiting; otherwise, ebusy is returned.


Detailed description

1. Initialization:

The data type used by the condition variable is pthread_cond_t. Initialization is required before use. Two methods are available:

  • Static: the constant pthread_cond_initializer can be assigned to the static conditional variable.
  • Dynamic: The pthread_cond_init function is used to clean up the memory space of the dynamic condition variable before it is released.

# Include <pthread. h>

Int pthread_cond_init (pthread_cond_t * restrict cond, pthread_condattr_t * restrict ATTR );
Int pthread_cond_destroy (pthread_cond_t * Cond );

If the call succeeds, 0 is returned. If the call fails, the error number is returned.

When the ATTR parameter of pthread_cond_init is null, a conditional variable of the default attribute will be created. It will be discussed after non-default conditions.

2. Waiting conditions:

# Include <pthread. h>

Int pthread_cond_wait (pthread_cond_t * restrict cond, pthread_mutex_t * restric mutex );
Int pthread_cond_timedwait (pthread_cond_t * restrict cond, pthread_mutex_t * restrict mutex, const struct timespec * restrict timeout );

If the call succeeds, 0 is returned. If the call fails, the error number is returned.

These two functions are respectively blocked wait and timeout wait.

The wait condition function waits for the condition to become true. The mutex passed to pthread_cond_wait protects the condition. The caller passes the locked mutex to the function. the function places the call thread on the list of threads waiting for the condition, and then unlocks the mutex. These two operations are atomic. in this way, the time channel between the condition check and the thread entering the sleep state waiting for the condition to change the two operations is closed, so that the thread will not miss any change in the condition.

When pthread_cond_wait returns, the mutex is locked again.

3. Notification conditions:

# Include <pthread. h>

Int pthread_cond_signal (pthread_cond_t * Cond );
Int pthread_cond_broadcast (pthread_cond_t * Cond );

If the call succeeds, 0 is returned. If the call fails, the error number is returned.

These two functions are used to notify the thread that the condition has been met. call these two functions, also known as sending signals to the thread or condition. You must note that you must send signals to the thread after changing the condition state.

Sample program
# Include <stdio. h> # include <pthread. h> pthread_mutex_t mutex; pthread_cond_t cond; void * thread1 (void * Arg) {pthread_cleanup_push (pthread_mutex_unlock, & mutex); // provides function callback protection while (1) {printf ("thread1 is running \ n"); pthread_mutex_lock (& mutex); pthread_cond_wait (& cond, & mutex); printf ("thread1 applied the condition \ n "); pthread_mutex_unlock (& mutex); sleep (4);} pthread_cleanup_pop (0);} void * thread2 (void * Arg) {While (1) {printf ("thread2 is running \ n"); pthread_mutex_lock (& mutex); pthread_cond_wait (& cond, & mutex ); printf ("thread2 applied the condition \ n"); pthread_mutex_unlock (& mutex); sleep (1) ;}} int main () {pthread_t thid1, thid2; printf ("condition variable study! \ N "); pthread_mutex_init (& mutex, null); pthread_cond_init (& cond, null); pthread_create (& thid1, null, (void *) thread1, null ); pthread_create (& thid2, null, (void *) thread2, null); do {pthread_cond_signal (& Cond) ;}while (1); sleep (20); pthread_exit (0 ); return 0 ;}

Differences between conditional variables, mutex locks, and semaphores

1. The mutex lock must always be unlocked by the lock thread. When the semaphore is mounted, it does not need to be executed by the same process that has executed its waiting operation. One thread can wait for a given signal lamp, while the other thread can mount the signal lamp.

2. The mutex lock is either locked or unlocked (Binary state, type binary semaphore ).

3. Because a semaphore has a State associated with it (its Count value), the semaphore hanging-out operation is always remembered. However, when sending a signal to a condition variable, if no thread is waiting on the condition variable, the signal will be lost.

4. mutex lock is designed for locking. conditional variables are designed for waiting. signals can be used for locking or waiting, which may lead to more overhead and higher complexity.

Reference: http://blog.csdn.net/dai_weitao/archive/2007/08/22/1754964.aspx

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.