Thread synchronization and Mutex conditions • variables

Source: Internet
Author: User

condition variable (condition variable )

Synchronization and mutex between threads are mainly based on mutual exclusion and conditional variables, and the combination of condition variables and mutual exclusion can well handle the synchronization problem between the threads waiting for the condition. For example: Consumer and producer issues.

& nbsp; The most basic relationship between consumers and producers is the relationship between service and service, but the relationship between access resources is emphasized in thread synchronization and mutual exclusion. First, the relationship between production and consumption is: , the relationship between production and production: Mutex , the relationship between consumption and consumption is: mutex. So there are two types of people who maintain these three kinds of relationships. : Producers and consumers. and production data and consumption data must have place .

Therefore, it is described as three kinds of relationship between two types of people a place (of course, the place here is not only one, can be diverse ).

Introduce several functions of the condition variable:

1. Define a condition variable

pthread_cond_t cond = Pthread_cond_initializer;

2. Initialize the condition variable (when the definition is not initialized)

int Pthread_cond_init (pthread_cond_t *restrict cond,

Const pthread_condattr_t *restrict attr);

3. Destroying condition variables

int Pthread_cond_destroy (pthread_cond_t *cond)

To raise a single consumer with a single producer problem:

  1  #include <stdio.h>  2  #include <pthread.h>  3 # include<assert.h>  4  #include <stdlib.h>  5 pthread_cond_t cond;   6 typedef int data_type;  7 pthread_mutex_t lock=pthread_mutex_ Initializer;  8 void push_node (Data_type data);   9 int pop_node () ;  10 void* producter (Void* arg)  11 { 12     data_ Type i=0; 13     while (1)  14    { 15        pthread_mutex_lock (&lock); 16        i++; 17       push_node (i); 18        sleep (2);  19       pthread_mutex_unlock (&lock);  20       printf ("product done......\n"); 21        sleep (2);  22       pthread_cond_signal (&cond); 23        sleep (2);  25     } 26  27  } 28 void *consumer (Void* arg)  29 { 30      Data_type res=-1; 31    while (1)  32    { 33        pthread_mutex_lock (&lock); 34        while ( -1==pop_node (&res))  35         { 36           pthread_cond_wait (&cond,&lock);  37           } 38          res=pop_node (&Amp;res);  39         printf ("consumer data: %d\n", RES);  40         sleep (2); 41          pthread_mutex_unlock (&lock); 44          pthread_cond_signal (&cond); 45          sleep (2);  46  47     } 48  49 } 50   51 typedef struct _node 52 { 53  data_type     _data; 54  struct _node* _next; 55 }node, *node_p,**node_ Pp; 56  57 node_p head=null; 58  static node_p buy_node (data _type data)  59 { 60    node_p tmp=malloc (sizeof (node));  61     if (tmp==nULL)  62      { 63         printf ("malloc failed\n"); 64  65       } 66       tmp->_data=data; 67      tmp->_next= Null; 68      return tmp; 69 } 71 void init_ List (node_pp phead)  72 { 73      *phead=buy_node (0);  74  } 75  76 void push_node (Data_type data)  77 { 78     79    if (head->_next==null)  80         head->_next=buy_node (data); 81    else{ 82       node_p tmp=buy_node (data);  83      tmp->_next= Head->_next; 84      head->_next=tmp; 85      } 86 }  87  88  89 int pop_node (Data_type *data)  90 { data_ Type ret=0; 91   92   if (head->_next==null)  93        return *data;      else{ 95     node_p tmp=head->_next; 96    head->_next=tmp->_next;  97    *data=tmp->_data; 98   free (TMP); 99     }100   return *data;101 }102 int main () 103 {104 105    init_list (&head); 106   pthread_cond_init (&cond,null);107    Pthread_mutex_init (&lock,null); 108   pthread_t tid1,tid2;109   pthread_ Create (&tid1,null,prodUcter,null); 110   pthread_create (&tid2,null,consumer,null); 111   pthread_ Join (Tid1,null); 112   pthread_join (tid2,null); 113   pthread_cond_destroy (& COND); 114   pthread_mutex_destroy (&lock);115   return 0;                                                                      }

Operation Result:


650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/7F/6D/wKiom1cd-vGxYyVwAAA9ryHJceI726.png "title=" client . PNG "alt=" Wkiom1cd-vgxyyvwaaa9ryhjcei726.png "/>

Results Analysis:

Producers produce a data that consumers can consume, and when there is no data in the list, consumers wait for the corresponding conditional variables and locks until they are released to consume.

Expansion: Multi-consumer and multi-producer issues

 10 pthread_mutex_t plock=pthread_mutex_initializer; 11 pthread_mutex_t conlock= Pthread_mutex_initializer; 12 void push_node (data_type data);  13 int pop_ Node ();  14 void* producter (Void* arg)  15 { 16      Data_type i=0; 17     while (1)  18    {   Sem_wait (&sem_product);  19       pthread_mutex_lock (&plock);  20       i++; 21       push_ node (i);  22       sleep (2); 23        pthread_mutex_unlock (&plock);  24       sem_post (& Sem_consume);  25       printf ("product done......\n");  26         sleep (2);  27      pthread_cond_signal (&cond);  28       sleep (2); 29  30      } 31  32 } 33 void *consumer (Void* arg)  34 { 35      data_type res=-1; 36    while (1)  37     { 38       sem_wait (&sem_consume); 39        pthread_mutex_lock (&conlock); 40        while ( -1==pop_node (&res))  41         {  42          pthread_cond_wait (&cond,&plock);  43           } 44          res=pop_node (&res);  45         printf ("consumer data: %d\n" , res);  46         sleep (2); 47          pthread_mutex_unlock (&conlock); 48  49          sem_post (&sem_product); 50  51          pthread_cond_signal (&cond); 52  53          sleep (2);  54  55     }






This article is from the "Output Diamond pattern" blog, so be sure to keep this source http://10541571.blog.51cto.com/10531571/1767657

Thread synchronization and Mutex conditions • variables

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.