Usage record of Linux c condition variable cond

Source: Internet
Author: User
Tags mutex

A conditional variable is a method for synchronizing between threads, which is used to automatically block a thread until it receives a cond signal or other special case, and the condition variable must be used in conjunction with the mutex when used, in order to guarantee the "atomicity" of the condition-to-thread operation.

1. Create a condition variable cond:

int Pthread_cond_init (pthread_cond_t * cond, const pthread_condattr_t * attr) ;

If attr is NULL when initializing a condition variable, the test uses the default value to initialize a condition variable cond, which is equivalent to defining a condition variable cond in the following way;

pthread_cond_t Cond = Pthread_cond_initializer;

2. Destroy a condition variable cond:

int Pthread_cond_destroy (pthread_cond_t *cond);

A condition variable cond can be destroyed so that it is not initialized. A referenced condition variable is not destroyed, and the consequences of using a destroyed conditional variable will be tested under the default conditions, which will cause the thread to be in a blocked state.

3. Wait for a condition variable:

int pthread_cond_timedwait (pthread_cond_t *cond, pthread_mutex_t *mutex, const struct TIMESPEC *restrict abstime);
int pthread_cond_wait (pthread_cond_t *restrict cond, pthread_mutex_t *restrict Mutex );

Will cause the thread to block in the condition variable cond, the application should ensure that the thread that is locked by the mutex calls these functions, otherwise it may cause an unknown error.

These two functions will automatically release the mutex at the start of execution, wait for the condition variable to automatically lock the mutex, and if there are other threads calling the mutex will cause the thread to block. The specific execution process is as follows:

Pthread_mutex_cond_unlock (mutex);

Pthread_cond_wait (cond);

Pthread_mutex_cond_lock (mutex);

Be sure to release the mutex before the thread that contains the pthread_cond_wait function ends, or else the thread that waits for cond is blocked. If another thread obtains the mutex mutex, it will also cause the cond thread to block.

4. Wake up a thread that is cond blocked:

int Pthread_cond_broadcast (pthread_cond_t *cond);
int pthread_cond_signal (pthread_cond_t *cond);

Pthread_cond_signal will wake up a blocked thread, pthread_cond_broadcast is waking up all blocked threads if there are no blocked threads pthread_cond_signal with Pthread_cond_ The broadcast will also return correctly, but the resulting signal will not play any role.

5, using pthread_cond_timedwait to achieve accurate delay, in a single thread of cond and mutexes can be directly in the following way to achieve accurate delay:

 

void Set_abswaittime (struct timespec*outtime, int ms)
{

Long sec;
Long usec;
struct Timeval tnow;
Gettimeofday (&tnow, NULL);
USEC = tnow.tv_usec + ms*1000;
SEC = tnow.tv_sec+usec/1000000;
Outtime->tv_nsec= (usec%1000000) *1000;
outtime->tv_sec=sec;
}


pthread_mutex_t mutex=pthread_mutex_initializer;pthread_cond_t Cond=Pthread_cond_initializer; struct timespec abstime;set_abswaittime (&abstime,;p) thread_cond_wait (&tcond, &tmutex, &abstime);

6, the condition variable uses the test, the test code is as follows:

// //founder: Levy//Time of Creation://function: Main.c//Copyright (c) Levy. All rights Reserved.//Ver Change Date owner change Content//──────────────────────────────────────────────────────────────────────────//V0.01, first edition of the levy// #include<stdlib.h>#include<stdio.h>#include<unistd.h>#include<time.h>#include<sys/time.h>#include<pthread.h>#include<string.h>#include<errno.h>pthread_mutex_t Test_mutex=pthread_mutex_initializer;pthread_cond_t Test_cond=Pthread_cond_initializer;intTest_count;void* TEST_THREAD1 (void*ARP) {    intS= (int) ARP; printf ("I am thread%ld, I'll sleep%d S. \ n", Pthread_self (), s);
Sleep (s); Pthread_mutex_lock (&Test_mutex); Pthread_cond_wait (&test_cond,&Test_mutex); Test_count++; printf ("My thread id is%ld, testcount=%d \ n", Pthread_self (), test_count); Pthread_mutex_unlock (&Test_mutex); Pthread_exit (NULL);}intMainvoid) {pthread_t th[3]; Test_count=0; for(intI=0;i<3; i++) {pthread_create (&th[i],null,test_thread1,i); } for(intI=0;i<3; i++) {
Sleep (3); Pthread_cond_signal (&Test_cond); } for(intI=0;i<3; i++) {pthread_join (th[i],null); } pthread_exit (NULL);}

Output Result:

I am thread 140391800571648, I'll sleep 1 s.
I am thread 140391808964352, I'll sleep 1 s.
I am thread 140391792178944, I'll sleep 1 s.
My thread ID is 140391808964352, testcount=1
My thread ID is 140391800571648, testcount=2
My thread ID is 140391792178944, testcount=3

If there is an error, please correct me!

Updated: 2017-06-02 15:54:50

Reference: http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_broadcast.html#tag_16_418

Usage record of Linux c condition variable cond

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.