Linux multithreaded Programming-condition variables

Source: Internet
Author: User

Condition variable

If the mutex between threads is used to synchronize access to shared data, then the condition variable is the value used to share data between threads. A condition variable provides a mechanism for notification between threads that wakes up a thread that waits for the shared data when a shared data reaches a certain value. There are 5 key correlation functions for conditional variables:

#include <pthread.h>int pthread_cond_init (pthread_cond_t *cond, const pthread_condattr_t *cond_attr); int Pthread_cond_destroy (pthread_cond_t *cond); int pthread_cond_broadcast (pthread_cond_t *cond); int Pthread_cond_ Signal (pthread_cond_t *cond); int pthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex);

The parameters of these functions cond point to the target semaphore to be manipulated, return 0 on success, and return an error code on error

L pthread_cond_init is used to initialize the condition variable, cond_attr specifies the property of the condition variable, or null to represent the default property, except that the Pthread_cond_init function is initialized with the You can also initialize this: pthread_cond_t cond= pthread_cond_initializer

L Pthread_cond_destroy is used to destroy a condition variable, destroying a waiting condition variable will fail and return Ebusy

L pthread_cond_broadcast wake up a thread with a wait condition variable in the form of a broadcast

L pthread_cond_signal is used to wake up a thread waiting for a condition variable, and as to which thread is awakened depends on the thread's priority and scheduling mechanism. Sometimes it is necessary to wake up a specified thread, but Pthread does not provide a workaround for that need. This requirement can be implemented indirectly by defining a global variable that uniquely represents the target thread, setting the variable as the target thread before waking the thread that waits for the condition variable, and then waking all the threads that wait for the condition variable in the broadcast form, after waking up to check whether the change is self, and if so, to start executing the subsequent code. Otherwise, continue to wait.

L pthread_cond_wait is used to wait for a condition variable, and the mutex parameter is used to protect the mutex of the condition variable to ensure the atomicity of the pthread_cond_wait operation. Before calling pthread_cond_wait, you must ensure that the mutex is locked, otherwise it will result in unpredictable consequences. When the Pthread_cond_wait function executes, the calling thread is first placed in the wait queue of the condition variable, and then the mutex is unlocked. As can be seen, pthread_cond_signal and pthread_cond_broadcast do not modify the condition variable during the time from pthread_cond_wait to its calling thread being put into the wait queue. That is, the pthread_cond_wait function does not miss any changes to the target condition variable, and when the Pthread_cond_wait function returns successfully, the mutex mutex will be locked again.


example of a program for a condition variable

#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define ERR_SYS (msg) do {perror (msg); exit (-1); The while (0) #define ERR_EXIT (msg) does {fprintf (stderr, msg); exit ( -1);} while (0) pthread_cond_t cond;void *r1 (void *arg) {PTH read_mutex_t* Mutex = (pthread_mutex_t *) arg;static int cnt = 10;while (cnt--) {printf ("r1:i am wait.\n");p Thread_mutex_lo CK (Mutex);p thread_cond_wait (&cond, mutex); /* The mutex parameter is used to protect the mutex of the condition variable, and the mutex must be locked */pthread_mutex_unlock (mutex) before calling Pthread_cond_wait;} Return "R1 over";} void *r2 (void *arg) {pthread_mutex_t* mutex = (pthread_mutex_t *) arg;static int cnt = 10;while (cnt--) {//pthread_mutex_ Lock (mutex); This place does not have a lock operation on the line printf ("R2:i am Send the Cond signal.\n");p thread_cond_signal (&cond);//pthread_mutex_unlock (mutex ); sleep (1);} Return "R2 over";} int main (void) {pthread_mutex_t mutex;pthread_t t1, t2;char* p1 = null;char* P2 = null;pthread_mutex_init (&mutex, NULL );p thread_cond_init (&cond, NULL);p thread_create (&t1, NULL, R1, &mutex);p thrEad_create (&t2, NULL, R2, &mutex);p thread_join (t1, (void * *) &p1);p Thread_join (T2, (void * *) &AMP;P2); Pthread_cond_destroy (&cond);p Thread_mutex_destroy (&mutex);p rintf ("S1:%s\n", p1);p rintf ("S2:%s\n", p2); return 0;}

Reference:

1,"Linux High Performance Server Programming," chapter 14th multithreaded Programming/condition Variables

2. Linux multithreaded programming

3, Linux multi-threaded programming-signal volume

4, Linux multi-threaded programming-Mutual exclusion lock



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Linux multithreaded Programming-condition variables

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.