Producer Consumers-(multi-threaded synchronization and mutual exclusion)

Source: Internet
Author: User

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.

/* Wait condition *//* Note: pthread_cond_wait is a blocking function. Unlock the lock, and then wait. When the condition is satisfied, it is necessary to grab the lock before it can be woken up *    /pthread_cond_wait (&COND_PRO,&MUTEX);/* Excitation condition *//* all threads that do not meet the condition will be blocked in the condition variable Cond_ In a queue in pro, *//* notifies all blocked threads */pthread_cond_broadcast (&cond_pro) in a broadcast manner, and/* Notifies only the first thread in signal mode */pthread_cond_ Signal (&COND_PRO);
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include < unistd.h> #define CELL 10#define flore 0int i = 0;              /* Global variables shared by all threads, which are assumed to increment to 10 at most, 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 thread resource is reclaimed by the system, not the main thread, which is a server and will never exit */while (1) {pthread_mutex_lock (&mutex); while(i >=CELL){pthread_cond_wait (&cond_pro,&mutex); /* Continue is polling, here is blocked *////////////////////////////Lock open and so on, the first parameter is struct pointer, where a member holds blocked function */* does not account for cpu*//* not satisfied        To be told, to awaken it *//* when it returns, the lock will come back. */} i++;    if (i = = 1) {/* from empty to not empty, wake up consumer */pthread_cond_signal (&cond_con);        /* does not immediately signal the blocked consumer thread, because it also waits for the lock to grab back */} printf ("Add I:%d \ n", i);        Pthread_mutex_unlock (&mutex);    Sleep (rand ()% 5 + 1);    }}/* Consumer thread */void* con_handler (void *arg) {Pthread_detach (pthread_self ()); while (1) {pthread_mutex_lock (&mutex); while(i <=Flore)        {pthread_cond_wait (&cond_cno,&mutex);        } i--;        if (i = = 9)/* from full to dissatisfied, to tell the producer so that it wakes *//* 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);    }}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 (&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));    int index = 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;}
Either in the producer thread or in the consumer thread. The judging condition of the yellow part of the mark must be used while. As a producer thread example, when I>=cell, that is I full, at this time to execute pthread_cond_wait (&cond_cno,&mutex); The producer thread is suspended. Must wait until the consumer thread pthread_cond_signal (&AMP;COND_PRO); To wake it up. But consumers will not be signal enough, the producer thread being hung must regain the lock before it can be activated. However, due to the consumer signal at the same time, the producer can not immediately grab the lock, so at this point may change the value of I will be greater than or equal to 10. Therefore, you must use while. Otherwise it may lead to i>10.

Further modification of the producer consumer model,

Producers and consumers (mutual exclusion and synchronization). The resource is simulated with a queue (to be locked, only one thread can operate the queue at a time).

M a producer. Get the lock, and product dissatisfaction, can be produced. When the product is full, wait for the consumer to wake up. When the product from empty to not empty, inform the consumer.
n a consumer. Get the lock, and have the product, in order to consume. When the product is empty, wait for the producer to wake up. When the product is filled to discontent, inform the producer.

Producer Conditions: Queue dissatisfaction
Consumer conditions: queue is not empty
So there are two conditional variables.

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include < Unistd.h> #define CNT 20/* Up to 20 products *//* with the queue simulation workshop *//* front and tail initialization are 0,tail is the next resource generated next array space subscript */typedef Stru   CT tag{int s_arr[cnt + 1];    /* Production of 20 products, there must be 21 space, because if the space is full of products, can not distinguish between the queue full and the queue empty */int s_front; int s_tail;} Queue,*pqueue; QUEUE my_que;/* Resource is empty */int Que_empty (Pqueue PQ) {return PQ->s_front = = PQ, S_tail;} /* Resource is full */int que_full (Pqueue PQ) {return (PQ-s_tail + 1)% (cnt+1) = = PQ--S_front;} int que_cnt (Pqueue PQ) {return (PQ-S_TAIL-PQ->s_front + cnt + 1)% (CNT + 1);} pthread_mutex_t Mutex;p thread_cond_t Cond_pro, Cond_con; void* Pro_handler (void* Arg) {Pthread_detach (pthread_self ())    ;        while (1) {pthread_mutex_lock (&mutex);        while (Que_full (&my_que)) {pthread_cond_wait (&cond_pro, &mutex); } My_que.s_arr[my_que.s_tail] = rand ()% 1000;       My_que.s_tail = (my_que.s_tail + 1)% (CNT + 1);        if (que_cnt (&my_que) = = 1) {pthread_cond_broadcast (&cond_con);        } printf ("Produce a product, total num:%d \ n", que_cnt (&my_que));        Pthread_mutex_unlock (&mutex);    Sleep (rand ()%3 + 1);    }}void* Con_handler (void* Arg) {Pthread_detach (pthread_self ());        while (1) {pthread_mutex_lock (&mutex);        while (Que_empty (&my_que)) {pthread_cond_wait (&cond_con, &mutex);        } My_que.s_front = (My_que.s_front + 1)% (CNT + 1); if (que_cnt (&my_que) = = CNT-1) {/* Because our main thread is waiting for the consumer thread to be created and then the producer thread is created, all consumer threads begin to hang at the beginning of the condition              The variable Cond_pro queue is therefore required to notify all consumer threads with broadcast.              Otherwise, a producer thread is notified, and the consumer thread grabs the lock. Of course, if the first mainline enters upgradeable creates a producer thread and then creates a consumer thread, because the producer threads are not all blocked, you can use signal to wake up a */Pthread_cond_broadcast (&am        P;cond_pro); } printf ("Consume a product, total num:%d \ n", que_cnt (&my_que));        Pthread_mutex_unlock (&mutex);    Sleep (rand ()%3 + 1);    }}int Main (int argc, char* argv[])//exe pro_num con_num{int con_cnt, pro_cnt;     My_que.s_front = 0;    My_que.s_tail = 0;    pro_cnt = Atoi (argv[1]);    con_cnt = Atoi (argv[2]);    Srand (Getpid ());    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));    int index = 0;        while (con_cnt > 0) {pthread_create (arr + index, NULL, Con_handler, NULL);        Index + +;    CON_CNT--;    } sleep (5);        while (pro_cnt > 0) {pthread_create (arr + index, NULL, Pro_handler, NULL);        Index + +;    PRO_CNT--;    } while (1);    Pthread_mutex_destroy (&mutex);    Pthread_cond_destroy (&cond_pro);    Pthread_cond_destroy (&cond_con); return 0;}

Makefile
MAIN:MAIN.C    gcc-o [email protected] $<-lpthread



Producer Consumers-(multi-threaded synchronization and mutual exclusion)

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.