Pthread threads (iii) thread synchronization--condition variables

Source: Internet
Author: User

Condition variable (Condition Variables)

Reference: http://game-lab.org/posts/posix-thread-cn/#5.1

What is a condition variable?

    • The condition variable gives us another way to synchronize between threads, however, the mutex is implemented synchronously by controlling the thread's access to the data, and the condition variable allows the thread synchronization to be based on the actual data value.
    • Without a condition variable, the programmer needs to keep the thread polling continuously to check if the condition is met. Because the thread is in an uninterrupted state of being busy, it is quite resource-intensive. A condition variable is one way to solve this problem without polling.
    • Conditional variables are always used with mutexes (mutex lock).
    • The following is a typical procedure for using conditional variables:
main thread
  • declares and initializes global data or variables that need to be synchronized (for example, "Count")
  • create threads A and B and start running
thread a
  • thread running to a condition is triggered (for example, "count" must reach a value)
  • Lock the associated mutex and check the value of the global variable
  • call Pthread_con_wait () to block the thread waiting for thread B's signal. Note that calling pthread_con_wait () unlocks the associated mutex in an automatic atomic manner (atomically) so that it can be used by thread B.
  • clear unlock mutex.
  • continue
Thread B
  • Thread operation
  • Locks the associated mutex amount
  • Changing the value of a global variable to which thread A is waiting
  • Check that thread a waits for a variable value, and if the condition is met, send a signal to thread a
  • Unlock Mutex Amount
  • Go on
Main Thread
    join/continue

Creating and destroying condition variables

Function:

Pthread_cond_init (condition,attr) Pthread_cond_destroy (condition) pthread_condattr_init (attr) pthread_condattr_ Destroy (attr)

Usage:

    • The condition variable must be declared as a pthread_cond_t type and must be initialized before it is used. Initialization, there are two methods:
  1. Static initialization, declared like this: pthread_con_t Myconvar = Pthread_con_initializer;
  2. Dynamic initialization, using the Pthread_cond_init () function. Pass the ID of the created condition variable to the thread as a parameter, which allows setting the condition Variable object property attr.
    • A attr object that can be set is often used to set the properties of a condition variable, which has only one property: Process-thread, which allows the condition variable to be seen by the threads of another process. If you use a Property object, you must be a pthread_condattr_t type (you can also assign a value of NULL as the default value).

Note that not all implementations have the process-shared attribute.

    • The Pthread_condattr_init () and Pthread_condattr_destroy () functions are used to create and destroy conditional variable Property objects.
    • When a condition variable is no longer needed, it can be destroyed with Pthread_cond_destroy ().

Wait and signal sending of condition variables

Function:

Pthread_cond_wait (Condition,mutex) pthread_cond_signal (condition) pthread_cond_broadcast (condition)

Use:

    • Pthread_cond_wait () blocks the calling thread until the specified condition variable receives a signal. When the mutex is locked, the function should be called, and the mutex is automatically freed when waiting, the thread is awakened after the signal is received, the mutex of the thread is automatically locked, and the programmer should unlock the mutex after this function.
    • The Pthread_cond_signal () function is commonly used to signal (or wake) another thread that is waiting for a condition variable, which should be called after the mutex is locked, and the mutex must be unlocked for the pthread_cond_wait () function to complete.
    • If multiple threads are in a blocking wait state, you must use the Pthreads_cond_broadcast () function instead of pthread_cond_signal ().
    • It is a logical error to call the Pthread_cond_signal () function before calling the Pthread_cond_wait () function, so it is necessary to properly lock and unlock the mutex associated with the condition variable when using these functions , for example:
  1. The lock mutex fails before calling Pthread_cond_wait (), which can cause it to be blocked;
  2. After calling Pthread_cond_signal () to unlock the mutex fails, the corresponding pthread_cond_wait () function cannot be completed and remains blocked.

Example Analysis

1 /******************************************************************************2 * Description:3 * Apply the instance code of the Pthreads condition variable, the main thread creates three threads, two of which are "count" variables do4 * Addition operation, the third thread monitors the value of "count". When "Count" reaches a qualified value, wait for the thread to be ready to receive5 * A signal from two addition threads waits for the thread to wake up and change the value of "count". The program continues to run until the addition6 * thread reaches the value of Tcount. Finally, the main program prints the value of count. 7  ******************************************************************************/8#include <pthread.h>9#include <stdio.h>Ten#include <stdlib.h> One  A #defineNum_threads 3 - #defineTCOUNT 5//single-thread polling times - #defineCount_limit 7//number of times the signal was sent the intCount =0;//Global Cumulative Amount -  - pthread_mutex_t Count_mutex; - pthread_cond_t COUNT_THRESHOLD_CV; +  - void*inc_count (void*t) { +     inti; A     Longmy_id = (Long) T; at  -      for(i =0; i < TCOUNT; i++) { -Pthread_mutex_lock (&Count_mutex); -count++; -         /* - * Check the value of count and send a signal to the waiting thread if the condition is met in * Note that this is locked with a semaphore.  -          * */ to         if(Count <count_limit) { +printf"inc_count (): Thread%ld, Count =%d Threshold reached.", - my_id, count); thePthread_cond_signal (&COUNT_THRESHOLD_CV); *printf"Just sent signal.\n"); $         }Panax Notoginsengprintf"inc_count (): Thread%ld, Count =%d, unlocking mutex\n", my_id, - count); thePthread_mutex_unlock (&Count_mutex); +  A         /*increase delay for thread polling mutex*/ theSleep1); +     } - Pthread_exit (NULL); $ } $  - void*watch_count (void*t) { -     Longmy_id = (Long) T; theprintf"starting Watch_count (): Thread%ld\n", my_id); - Wuyi     /*Lock the mutex and wait for the signal, note that the Pthread_cond_wait function automatically atomically when waiting the * Unlock the mutex amount. Also, note that if the wait thread runs until the wait function has satisfied the Count_limit - * Conditional judgment, polling ignores the wait function, Wu      * */ -      while(Count <count_limit) { AboutPthread_mutex_lock (&Count_mutex); $printf"watch_count (): Thread%ld going into wait...\n", my_id); -Pthread_cond_wait (&AMP;COUNT_THRESHOLD_CV, &Count_mutex); -printf"watch_count (): Thread%ld Condition signal received.\n", my_id); -  Aprintf"watch_count (): Thread%ld count now =%d.\n", my_id, count); +Pthread_mutex_unlock (&Count_mutex); the     } - Pthread_exit (NULL); $ } the  the intMainintargcChar*argv[]) { the     inti; the     LongT1 =1, t2 =2, T3 =3; -pthread_t threads[3]; in pthread_attr_t attr; the  the     /*initializing mutex and condition variable objects*/ AboutPthread_mutex_init (&Count_mutex, NULL); thePthread_cond_init (&COUNT_THRESHOLD_CV, NULL); the  the     /*set to connect when creating threads for portability*/ +Pthread_attr_init (&attr); -Pthread_attr_setdetachstate (&attr, pthread_create_joinable); thePthread_create (&threads[0], &attr, Watch_count, (void*) t1);BayiPthread_create (&threads[1], &attr, Inc_count, (void*) t2); thePthread_create (&threads[2], &attr, Inc_count, (void*) t3); the  -     /*wait for all threads to complete*/ -      for(i =1; i < num_threads; i++) { the Pthread_join (Threads[i], NULL); the     } the    /*send a signal to a listener thread*/ thePthread_cond_signal (&COUNT_THRESHOLD_CV);  -Pthread_join (threads[0],null); theprintf"Main (): Waited on%d threads. Final value of Count =%d. done.\n", the num_threads, count); the 94     /*Clear and Exit*/ thePthread_attr_destroy (&attr); thePthread_mutex_destroy (&Count_mutex); thePthread_cond_destroy (&COUNT_THRESHOLD_CV);98 Pthread_exit (NULL); About}

Pthread threads (iii) thread synchronization--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.