Linux multi-thread synchronization

Source: Internet
Author: User
Tags mutex printf rand sleep thread

Introduction

A condition variable is a mechanism for synchronizing a global variable shared between threads, consisting mainly of two actions: one thread waits for the condition variable to hang (the CPU is no longer in use), and another thread makes the condition (giving the conditional signal). To prevent competition, the use of conditional variables is always combined with a mutex.

Function prototypes

1. Define a condition variable

#include <pthread.h>/* defines two conditional variables */pthread_cond_t cond_pro, Cond_con;

2. Initialization and destruction of condition variables

#include <pthread.h>int pthread_cond_init (pthread_cond_t *restrict cond, const pthread_condattr_t *RESTRICT );
int Pthread_cond_destroy (pthread_cond_t *cond);
/* Initialize condition variable */pthread_cond_init (&cond_pro, NULL);p thread_cond_init (&cond_con, NULL);/* Destroy condition variable */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 wait. When the conditions are met, it is necessary to grab the lock before it can be awakened    /pthread_cond_wait (&COND_PRO,&MUTEX);/* Excitation condition *//* all threads that do not meet the condition will block in the condition variable Cond_ In a queue in pro, *//* broadcasts, notifying all blocked threads */pthread_cond_broadcast (&cond_pro), and/or signal, notifying only the threads at the front of the line */pthread_cond_ Signal (&COND_PRO);

Code

/************************************************************************* &gt; File name:my_con.c &gt; Author:kr Ischou &gt; Mail:zhoujx0219@163.com &gt; Created time:tue Aug 2014 10:24:29 AM CST **************************** /#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt; string.h&gt; #include &lt;pthread.h&gt; #include &lt;unistd.h&gt; #define CELL 10#define flore 0int i = 0;              /* All threads share global variables, where it is assumed to increment up to 10 and minimize to 0 */pthread_mutex_t mutexes;  /* Define mutual exclusion lock */pthread_cond_t Cond_pro, Cond_con;   /* Define two condition variables *//* producer thread */void* pro_handler (void *arg) {Pthread_detach (pthread_self ());        /* The system reclaims the thread resource, not the main thread, which is a server and will never quit/while (1) {pthread_mutex_lock (&amp;mutex);             while (i &gt;= CELL) {pthread_cond_wait (&amp;cond_pro,&amp;mutex); /* Continue is polling, here is blocking///* Unlock the lock and so on, the first parameter is the structure of the pointer, which has a member to store the blocked function * * * does not account for cpu*//* not meet the conditions will wait, need should notPeople tell it to wake it *//* when it returns, the lock will come back/} i++;    if (i = = 1) {/* from empty to not empty, wake-up consumer * * * pthread_cond_signal (&amp;cond_con);        /* will not immediately signal the blocked consumer thread, because it also has to wait for the lock to grab back/printf ("Add I:%d/n", i);        Pthread_mutex_unlock (&amp;mutex);    Sleep (rand ()% 5 + 1);    }}/* Consumer thread */void* con_handler (void *arg) {Pthread_detach (pthread_self ());        while (1) {pthread_mutex_lock (&amp;mutex);        while (i &lt;= Flore) {pthread_cond_wait (&amp;cond_cno,&amp;mutex);        } i--;        if (i = = 9)/* from full to dissatisfied, to tell the producer so that it wakes *//* here, direct signal also can, we are in order to more precise * * pthread_cond_signal (&AMP;COND_PRO);        printf ("Con i:%d/n", i);        Pthread_mutex_unlock (&amp;mutex);    Sleep (rand ()% 5 + 1);    }}int Main (int argc, char *argv[])/exe +num-num{Srand (Getpid ());    int con_cnt, pro_cnt;    pro_cnt = Atoi (argv[1]);    con_cnt = Atoi (argv[2]);    Pthread_mutex_init (&amp;mutex,null); PThread_cond_init (&amp;cond_pro,null);    Pthread_cond_init (&amp;cond_con,null);    pthread_t *arr = (pthread_t*) calloc (con_cnt + pro_cnt, sizeof (pthread_t));    int index = 0;        while (pro_cnt &gt; 0) {pthread_create (arr + index, NULL, Pro_handler, NULL);        index++;    pro_cnt--;        while (con_cnt &gt; 0) {pthread_create (arr + index, NULL, Con_handler, NULL);        index++;    con_cnt--;    while (1);    Pthread_mutex_destroy (&amp;mutex);    Pthread_cond_destroy (&amp;cond_pro);    Pthread_cond_destroy (&amp;cond_con); return 0;}

Attention

Either in the producer thread or in the consumer thread. The criteria for marking the yellow part must be in the while. In the case of producer threads, when I>=cell, that is, I full, execute pthread_cond_wait (&cond_cno,&mutex) at this time; The producer thread is suspended. Must wait until the consumer thread pthread_cond_signal (&COND_PRO); To wake it up. But the consumer is not enough to signal it, the producer thread that is linked must regain the lock before it can be activated. However, because the consumer signal, the producer can not immediately grab the lock, so at this time may change the I value is greater than or equal to 10. Therefore, you must use a while. Otherwise it may lead to i>10.

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.