Linux multi-thread synchronization

Source: Internet
Author: User

Introduction

Conditional variables are a mechanism for synchronizing with global variables shared between threads, consisting of two actions: one thread waits for a condition variable to be set up and hangs (no longer consumes the CPU at this time), and the other thread makes the condition (given a condition signal). To prevent competition, the use of condition variables is always combined with a mutex. Function prototypes

1. Defining Condition Variables

#include <pthread.h>/*/pthread_cond_t Cond_pro, Cond_con;

2. Initializing and destroying condition variables

#include <pthread.h>int pthread_cond_init (pthread_cond_t *const PTHREAD_CONDATTR_ T *restrict attr);
intPthread_cond_destroy (pthread_cond_t *cond);
/**/pthread_cond_init (&Cond_pro, NULL);p thread_cond_init (&  Cond_con, NULL); /*  */Pthread_cond_destroy (&Cond_pro);p Thread_cond_destroy (&cond_ PRO);

3. Waiting and excitation conditions

#include <pthread.h>int pthread_cond_wait (pthread_cond_t *restrict cond,  pthread_mutex_t *  Restrict mutex); int pthread_cond_broadcast (pthread_cond_t *cond); int pthread_cond_signal (pthread_cond_t *cond);
/*Wait Condition*//*Note: pthread_cond_wait is a blocking function. Unlock the lock, and then wait. When the condition is met, the lock needs to be grabbed before it can be awakened.*/pthread_cond_wait (&cond_pro,&mutex); /*Excitation conditions*//*all threads that do not meet the criteria will be blocked in a queue in the condition variable Cond_pro*//*notify all blocked threads in broadcast mode*/Pthread_cond_broadcast (&Cond_pro);/*In signal mode, only the thread in front of the queue is notified*/pthread_cond_signal (&cond_pro);
Code
/************************************************************************* > File name:my_con.c > Author:k Rischou > Mail:[email protected] > Created time:tue-10:24:29 AM CST **************************** ********************************************/#include<stdio.h>#include<stdlib.h>#include<string.h>#include<pthread.h>#include<unistd.h>#defineCELL 10#defineFlore 0inti =0;/*Global variables shared by all threads, which are assumed to be incremented up to 10 at least, to a minimum of 0*/pthread_mutex_t Mutex; /*Defining Mutex Locks*/pthread_cond_t Cond_pro, Cond_con; /*define two condition variables*//*Producer Threads*/void* Pro_handler (void*Arg)   {Pthread_detach (pthread_self ()); /*The system recycles the thread resources, not the main thread, which is a server and never quits*/         while(1) {Pthread_mutex_lock (&mutex); if(I >=CELL) {pthread_cond_wait (&cond_pro,&mutex); /*Continue is polling, here is blocking*/            /*let go of the lock, wait, the first parameter is a struct pointer, where a member holds the blocked function*/            /*does not account for CPU*/            /*not meet the conditions will wait, need someone to tell it, to wake it*//*when it returns, the lock is coming back.*/} i++; if(i = =1)        {            /*from empty to not empty, wake up the consumer*/pthread_cond_signal (&cond_con);/*will not immediately signal the blocked consumer thread, because it has to wait for the lock to grab back*/} printf ("add I:%d \ n", i); Pthread_mutex_unlock (&mutex); Sleep (rand ()%5+1); }}/*Consumer Threads*/void* Con_handler (void*Arg)    {Pthread_detach (pthread_self ());  while(1) {Pthread_mutex_lock (&mutex); if(I <=Flore) {pthread_cond_wait (&cond_cno,&mutex); } I--; if(i = =9)/*from full to dissatisfied, to tell the producer so that it would wake up*//*here, direct signal can also, we are for more accurate*/{pthread_cond_signal (&Cond_pro); } printf ("con i:%d \ n", i); Pthread_mutex_unlock (&mutex); Sleep (rand ()%5+1); }}intMainintargcChar*argv[])//exe +num-num{Srand (Getpid ()); intcon_cnt, pro_cnt; Pro_cnt= Atoi (argv[1]); Con_cnt= Atoi (argv[2]); Pthread_mutex_init (&mutex,null); Pthread_cond_init (&cond_pro,null); Pthread_cond_init (&cond_con,null); pthread_t*arr = (pthread_t*) calloc (con_cnt + pro_cnt,sizeof(pthread_t)); intindex =0;  while(Pro_cnt >0) {pthread_create (arr+index, NULL, Pro_handler, NULL); Index++; Pro_cnt--; }     while(Con_cnt >0) {pthread_create (arr+index, NULL, Con_handler, NULL); Index++; Con_cnt--; }     while(1); Pthread_mutex_destroy (&mutex); Pthread_cond_destroy (&Cond_pro); Pthread_cond_destroy (&Cond_con); return 0;}

Linux multi-thread synchronization

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.