Linux thread synchronization condition variable usage

Source: Internet
Author: User

À background knowledge

1 mutex

Mutex Functions

Pthread_mutex_init initializes a mutex

Pthread_mutex_lock lock a mutex

Pthread_mutex_trylock lock, if the failure is not blocked

Pthread_mutex_unlock unlock

In essence, mutex is a lock. A lock is applied to the mutex before accessing shared resources, and the lock on the mutex is released after the access is complete. After the mutex is locked, any other thread that tries to lock the mutex again will be blocked until the current thread releases the mutex.

2. Condition Variables

Use the pthread_cond_initializer constant in static mode, as follows:
Pthread_cond_t cond = pthread_cond_initializer
Call the pthread_cond_init () function dynamically. The API is defined as follows:
Pthread_cond_init

Pthread_cond_wait: unconditional waiting
Ipthread_cond_timedwait timing wait

Pthread_cond_signal () activates a thread waiting for this condition. When there are multiple waiting threads, one of them is activated in the queue order.

Pthread_cond_broadcast () activates all waiting threads.

Conditional variables implement a notification mechanism. First, call pthread_cond_wait (Cond, mutex) in thread B to wait for the conditional variable to be triggered and B will be blocked in pthread_cond_wait until it is not activated, once pthread_cond_signal () is called in thread, that is to say, when the condition variable of the notification thread B is available, pthread_cond_wait changes from blocking to execution state (during execution, mutex first unlock-> wait return-> mutexlock ).

À relationship between mutex and condition Variables

1. To ensure that thread a sends a notification to conditional variables, thread B receives the notification in sequence. Make sure that B blocks pthread_cond_wait after a conditional variable notification has been issued at the previous time. (To achieve this, mutex is a good choice ).

2. If there is no mutex, the main () access may cause competition when thread_func accesses critical resources.

À paste an example:

 

# Include <pthread. h> # include <unistd. h> static pthread_mutex_t CTX = pthread_mutex_initializer; static pthread_cond_t cond = pthread_cond_initializer; struct node {int n_number; struct node * n_next;} * head = NULL; /* [thread_func] */static void cleanup_handler (void * Arg) {printf ("cleanup handler of second thread. /n "); free (ARG); (void) pthread_mutex_unlock (& Arg);} static void * thread_func (void * Arg) {struct Node * P = NULL; pthread_cleanup_push (cleanup_handler, P); While (1) {pthread_mutex_lock (& CTX); While (Head = NULL) {// This while clause should be noted that a single pthread_cond_wait has excellent functions. Why is there a while (Head = NULL? Because the threads in pthread_cond_wait may be accidentally awakened, if this time head! = NULL is not what we want. At this time, the thread should continue to enter pthread_cond_wait (& cond, & CTX); // pthread_cond_wait will first remove the previously locked pthread_mutex_lock's content, and then block waiting for sleep in the column, wait until it is awakened again (in most cases, the waiting condition is set up, and then the process will first lock pthread_mutex_lock (& CTX );, read the resource again // use this process to be clear/* block --> unlock --> wait () return --> lock */} p = head; head = head-> n_next; printf ("got % d from front of queue/N", p-> n_number); free (p); pthread_mutex_unlock (& CTX ); // The data operation in the critical section is completed, and the mutex lock is released} PTH Read_cleanup_pop (0); Return 0;} int main (void) {pthread_t tid; int I; struct node * P; pthread_create (& tid, null, thread_func, null ); /* [tx6-main] */for (I = 0; I <10; I ++) {P = malloc (sizeof (struct node); P-> n_number = I; pthread_mutex_lock (& CTX); // The head critical resource needs to be operated. Lock the resource first. P-> n_next = head; head = P; pthread_cond_signal (& Cond ); pthread_mutex_unlock (& CTX); // unlock sleep (1);} printf ("thread 1 wanna end The line. so cancel thread 2. /n "); pthread_cancel (TID); // For pthread_cancel, there is an additional description. It ends the child thread from the external end. The child thread will exit the thread at the latest cancellation point, in our code, the recent cancellation point must be pthread_cond_wait. For details about the cancellation point, Google is recommended. pthread_join (TID, null); printf ("all done -- exiting/N"); Return 0;} is not mentioned here ;}

Http://blog.csdn.net/hairetz/article/details/4535920

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.