"Linux Advanced Programming" (12th) Linux multithreaded Programming 3

Source: Internet
Author: User

Conditional variable communication mechanism

Conditional variables must implement mutually exclusive access to the resource together with the mutex

How to use:

int Pthread_cond_init (pthread_cond_t *__restrict __cond, __const pthread_condattr_t *__restrict __cond_attr) : initializes a condition variable, the second argument is a Property object, and Null is the default

int Pthread_cond_destroy (pthread_cond_t *__cond) : destroy condition variable

int pthread_cond_signal (pthread_cond_t *__cond) : notifies the first thread of the wait condition variable , which does not work if there are no waiting threads

int Pthread_cond_broadcast (pthread_cond_t *__cond) : notifies all threads waiting for a condition variable , if there is no waiting thread, it does not work

int pthread_cond_wait (pthread_cond_t *__restrict __cond, pthread_mutex_t *__restrict __mutex) : Wait condition variable , the second argument points to the mutex pointer associated with the condition variable

int pthread_cond_timewait (pthread_cond_t *__restrict __cond, pthread_mutex_t *__restrict __mutex, __const struct Timespec *__restrict __ Abstime) : waits for a condition variable within a specified time .

When an online routines waits for a condition variable to enter a wait state, its requested mutex is freed. When you wait for a condition variable, you implicitly request the mutex

Conditional variables implement read-write locks

#include <stdio.h>#include<stdlib.h>#include<time.h>#include"pthread.h"#defineBuffer_size 2//conditional information Structure Bodystructprodcons{intBuffer[buffer_size];//Production Product Valuepthread_mutex_tLock;//Mutual exclusion Lock    intReadpos, Writepos;//Read and write locationspthread_cond_t Notempty;//condition variable, table non-emptypthread_cond_t Notfull;//condition variable, table is not full};//InitializevoidInitstructProdcons *prod) {Pthread_mutex_init (&prod->Lock, NULL); Pthread_cond_init (&prod->Notempty, NULL); Pthread_cond_init (&prod->Notfull, NULL); Prod->readpos =0; Prod->writepos =0;}//Enter a data in the buffervoidPutstructProdcons * PROD,intdata) {    //Lock MutexPthread_mutex_lock (&prod->Lock);  while((Prod->writepos +1)% Buffer_size = = Prod->readpos)//test whether the space is full note that the position of the writepos here to add 1 is to ensure that the next write location is empty?? {printf ("producer wait for not full\n"); Pthread_cond_wait (&prod->notfull, &prod->Lock);//waiting for a space to write    }    //Write DataProd->buffer[prod->writepos] =data; Prod->writepos++; if(Prod->writepos >=buffer_size) Prod->writepos =0; Pthread_cond_signal (&prod->notempty); Pthread_mutex_unlock (&prod->Lock);}//read a data from a bufferint Get(structProdcons *prod) {    intdata; //Lock MutexPthread_mutex_lock (&prod->Lock);  while(Prod->writepos = = prod->Readpos) {printf ("producer wait for not empty\n"); Pthread_cond_wait (&prod->notempty, &prod->Lock); } Data= prod->buffer[prod->Readpos]; Prod->readpos++; if(Prod->readpos >=buffer_size) Prod->readpos =0; Pthread_cond_signal (&prod->notfull); Pthread_mutex_unlock (&prod->Lock); returndata;}#defineOver (-1)structprodcons buffer;//producersvoid* Producer (void*data) {    intN;  for(n =1; N <=5; n++)//production of 5 products{printf ("producer Sleep 1 second...\n"); Sleep (1); printf ("put the%d product\n", N); Put (&buffer, n); }     for(n =6; N <=Ten; n++) {printf ("producer Sleep 3 second...\n"); Sleep (3); printf ("put the%d product\n", N); Put (&buffer, n); } put (&buffer, over); printf ("producer Stopped!\n"); returnNULL;}//Consumervoid* Consumer (void*data) {    intD =0;  while(1) {printf ("Consumer Sleep 2 second...\n"); Sleep (2); D=Get(&buffer); printf ("get the%d product\n", D); if(d = =Over ) Break; } printf ("Consumer stopped!\n"); returnNULL;}intMainintargcChar*argv[])    {pthread_t th_a, th_b; void*retval; Init (&buffer); Pthread_create (&th_a, NULL, producer,0); Pthread_create (&th_b, NULL, Consumer,0); Pthread_join (Th_a,&retval); Pthread_join (Th_b,&retval); return 0;}

Validation, available

"Linux Advanced Programming" (12th) Linux multithreaded Programming 3

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.