Home Backend Development PHP Tutorial Linux--Condition Variable (condition variable) implements producer-consumer model and read-write lock

Linux--Condition Variable (condition variable) implements producer-consumer model and read-write lock

Jan 18, 2017 am 10:29 AM

1. Condition variables
During the thread synchronization process, there are also the following situations: thread A needs to wait for a certain condition to be established before it can continue execution. If the condition is not established, thread A will block while thread B is executing. When this condition is established during the process, thread A is awakened to continue execution. Use condition variables in the Pthread library to block waiting for a condition, or to wake up the thread waiting for this condition. Condition variables are represented by variables of type pthread_cond_t.

Use pthread_cond_init to initialize the condition variable. If the condition variable is statically allocated, you can also use the macro definition PTHEAD_COND_INITIALIZER to initialize it, and use pthread_cond_destroy to destroy the condition variable; 0 is returned on success, and an error number is returned on failure.
A condition variable is always used with a Mutex. A thread can call pthread_cond_wait to block and wait on a condition variable. This function does the following three steps:
1. Release the Mutex
2. Block and wait
3. When awakened, reacquire the Mutex and return
A thread can call pthread_cond_signal to wake up another thread waiting on a certain condition variable, or it can call pthread_cond_broadcast to wake up all threads waiting on this condition variable.
2. Use the producer-consumer model to illustrate
As the name suggests, it can be seen that to implement this model, you must first have two roles (producer, consumer). In addition to the two roles, of course There must be an occasion for both critical resources to be accessible (one occasion), and the relationship between producers (mutual exclusion) and the relationship between consumers (mutual exclusion) must be understood. , the relationship between producers and consumers (synchronization and mutual exclusion), in general, is one place, two roles, and three relationships. To implement it with code, the producer produces a piece of data and then sends a signal to the consumer to consume. After the consumer consumes it, it sends a signal to the producer to tell the producer to continue producing, and so on.

1 #include<stdio.h>  
  2 #include <stdlib.h>  
  3 #include<malloc.h>  
  4 #include<pthread.h>                                                                                                                               
  5 #include<semaphore.h>  
  6 typedef int Data_type;  
  7 typedef int* Data_type_p;  
  8 static pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;//初始化互斥锁  
  9 static pthread_cond_t needProduct=PTHREAD_COND_INITIALIZER;//初始化条件变量  
 10   
 11  
 12 typedef struct listnode //定义一个链表来存放数据(一个场所)  
 13 {  
 14     Data_type data;  
 15     struct listnode* next;  
 16 }list ,*listp,**listpp;  
 17   
 18 listp head=NULL;  
 19   
 20 static listp buyNode(Data_type _data)  
 21 {  
 22     listp tem=(listp)malloc(sizeof(list));  
 23     if(tem)  
 24     {  
 25         tem -> data=_data;  
 26         tem -> next=NULL;  
 27         return tem;  
 28     }  
 29     return NULL;  
 30 }  
 31 void initList(listpp list)  
 32 {  
 33     *list=buyNode(0);  
 34 }  
 35 void push_list(listp list,Data_type _data)  
 36 {  
 37     listp cur=buyNode(_data);  
 38     listp tem=list;  
 39     while(tem->next)  
 40     {  
 41         tem=tem->next;  
 42     }  
 43     tem ->next=cur;  
 44 }  
 45 void deleteList(listp list)  
 46 {  
 47     if(list)  
 48     {  
 49         free(list);  
 50         list=NULL;  
 51     }  
 52 }  
 53 int pop_list(listp list,Data_type_p data)  
 54 {  
 55     if(list ->next==NULL)  
 56     {  
 57         *data =-1;  
 58         return -1;  
 59     }  
 60     listp tem=list->next;  
 61     list ->next=tem->next;  
 62     *data=tem->data;  
 63     deleteList(tem);  
 64     return 0;  
 65 }  
 66 void PrintList(listp list)  
 67 {  
 68     listp cur=list->next;;  
 69     while(cur)  
 70     {  
 71         printf("%d",cur->data);  
 72         fflush(stdout);  
 73         cur=cur->next;  
 74     }  
 75     printf("\n");  
 76 }  
 77 void *product(void* arg)//定义生产者与生产者之间的关系(互斥)  
 78 {  
 79     int i=0;  
 80     while(1)  
 81     {  
 82         pthread_mutex_lock(&lock);  
 83         printf("product data:%d\n",i);  
 84         push_list(head,i++);  
 85         pthread_mutex_unlock(&lock);  
 86         printf("conduct is ok.weak up comsumer...\n");  
 87         pthread_cond_signal(&needProduct);//当生产者有数据时,发送信号,唤醒消费者  
 88         sleep(2);  
 89     }  
 90   
 91 }  
 92 void *consumer(void* arg)//消费者与消费者之间的关系(互斥)  
 93 {  
 94     Data_type _data;  
 95     while(1)  
 96     {     
 97         pthread_mutex_lock(&lock);  
 98         while(-1==pop_list(head,&_data))  
 99         {  
100             pthread_cond_wait(&needProduct,&lock);//没收到生产者的消息之前就阻塞等待  
101         }  
102         printf("consumer data:%d\n",_data);  
103         pthread_mutex_unlock(&lock);  
104         sleep(1);  
105     }  
106 }  
107 int main()  
108 {  
109     initList(&head);  
110     pthread_t id1;  
111     pthread_t id2;  
112     pthread_create(&id1,NULL,product,NULL);  
113     pthread_create(&id2,NULL,consumer,NULL);  
114     pthread_join(id1,NULL);  
115     pthread_join(id2,NULL);  
116     return 0;  
117 }
Copy after login

Summary: The above code implements a single producer and a single consumer, the producer-consumer model. Simply put, it is to achieve mutual exclusion between producers and producers, consumers and consumers There is a mutually exclusive relationship between producers and consumers, and a synchronized mutually exclusive relationship between producers and consumers.

3. Use semaphores to implement the producer-consumer model
Mutex variable is either 0 or 1, which can be regarded as the available quantity of a resource. When initialized, Mutex is 1, indicating that there is an available resource. ,
Obtain the resource when locking, reduce Mutex to 0, indicating that there is no more available resource, release the resource when unlocking, and add Mutex back to 1, indicating that there is another available resource. Semaphore is similar to Mutex and represents the number of available resources. Unlike Mutex, this number can be greater than 1. That is, if the number of resources described by the semaphore is 1, the semaphore and mutex lock at this time are the same!
sem_init()Initialize the semaphore

sem_wait()P operation to obtain resources

sem_post()V operation to release resources

sem_destroy()Destroy the semaphore

The above is a producer-consumer model written in a linked list, and its space is dynamically allocated. Now the producer-consumer model is rewritten based on a fixed-size ring queue

1 #include<stdio.h>  
  2 #include<pthread.h>  
  3 #include<semaphore.h>  
  4 #define PRODUCT_SIZE 20  
  5 #define CONSUMER_SIZE 0  
  6   
  7 sem_t produceSem;  
  8 sem_t consumerSem;  
  9 int Blank [PRODUCT_SIZE];  
 10   
 11 void* product(void* arg)  
 12 {  
 13     int p=0;  
 14     while(1)  
 15     {  
 16         sem_wait(&produceSem); //申请资源。  
 17         int _product=rand()%100;  
 18         Blank[p]=_product;  
 19         printf("product is ok ,value is :%d\n",_product);  
 20         sem_post(&consumerSem);//释放资源  
 21         p=(p+1) % PRODUCT_SIZE;  
 22         sleep(rand()%3);  
 23     }  
 24   
 25 }  
 26 void* consumer(void* arg)  
 27 {  
 28     int p=0;  
 29     while(1)  
 30     {  
 31         sem_wait(&consumerSem);//申请资源  
 32         int _consumer=Blank[p];  
 33         printf("consumer is ok,value is :%d\n",_consumer);  
 34         sem_post(&produceSem);//释放资源  
 35         p=(p+1)% PRODUCT_SIZE;  
 36         sleep(rand()%5);  
 37     }  
 38 }  
 39 int main()  
 40 {   sem_init(&produceSem,0,PRODUCT_SIZE);  
 41     sem_init(&consumerSem,0,CONSUMER_SIZE);  
 42     pthread_t tid1,tid2;  
 43     pthread_create(&tid1,NULL,product,NULL);  
 44     pthread_create(&tid2,NULL,consumer,NULL);  
 45     pthread_join(tid1,NULL);  
 46     pthread_join(tid2,NULL);  
 47     sem_destroy(&produceSem);  
 48     sem_destroy(&consumerSem);  
 49     return 0;  
 50 }
Copy after login

4. Read-write lock
The read-write lock is actually a special spin lock, used to deal with the situation of more reading and less writing. It divides visitors to shared resources into readers and writers. Readers only have read access to shared resources. Writers need to write to shared resources. This kind of lock can improve concurrency compared to spin locks, because in a multi-processor system, it allows multiple readers to access shared resources at the same time, and the maximum possible number of readers is the actual number of logical CPUs. Writers are exclusive. A read-write lock can only have one writer or multiple readers at the same time (related to the number of CPUs), but it cannot have both readers and writers at the same time. Read-write locks also follow three relationships: reader-writer (mutually exclusive and synchronized), reader-reader (no relationship), writer-writer (mutually exclusive) 2 objects (reader and writer), 1 location .
pthread_rwlock_wrlock Write mode, returns 0 on success, error code on failure

pthread_rwlock_rdlock Read mode, returns 0 on success, error code on failure

pthread_rwlock_init initialization

1 #include<stdio.h>  
  2 #include<pthread.h>  
  3 #define _READNUM_ 2  
  4 #define _WREITENUM_ 3  
  5 pthread_rwlock_t lock;  
  6 int buf=0;  
  7 void* read(void* reg)  
  8 {  
  9     while(1)  
 10     {  
 11         if(pthread_rwlock_tryrdlock(&lock) != 0)//读方式  
 12         {  
 13             printf("writer is write! reader wait...\n");  
 14         }  
 15         else  
 16         {  
 17             printf("reader is reading,val is %d\n",buf);  
 18             pthread_rwlock_unlock(&lock);  
 19         }  
 20         sleep(2);  
 21     }  
 22 }  
 23 void* write(void* reg)  
 24 {  
 25     while(1)  
 26     {  
 27         if(pthread_rwlock_trywrlock(&lock) != 0)//写方式  
 28         {  
 29             printf("reader is reading ! writer wait...\n");  
 30             sleep(1);  
 31         }  
 32         else  
 33         {  
 34             buf++;  
 35             printf("writer is writing,val is %d\n",buf);  
 36             pthread_rwlock_unlock(&lock);  
 37   
 38         }  
 39         sleep(1);  
 40     }  
 41 }  
 42 int main()  
 43 {  
 44     pthread_rwlock_init(&lock,NULL);  
 45     pthread_t tid;  
 46     int i=0;  
 47     for(i;i< _WREITENUM_;i++)  
 48     {  
 49         pthread_create(&tid,NULL,write,NULL);  
 50     }  
 51   
 52     for(i; i< _READNUM_;i++)  
 53     {  
 54         pthread_create(&tid,NULL,read,NULL);  
 55     }  
 56         pthread_join(tid,NULL);  
 57         sleep(100);  
 58         return 0;  
 59 }
Copy after login

The above is Linux--Condition Variable (condition variable) implements the producer-consumer model and read-write lock content. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
Linux Architecture: Unveiling the 5 Basic Components Linux Architecture: Unveiling the 5 Basic Components Apr 20, 2025 am 12:04 AM

The five basic components of the Linux system are: 1. Kernel, 2. System library, 3. System utilities, 4. Graphical user interface, 5. Applications. The kernel manages hardware resources, the system library provides precompiled functions, system utilities are used for system management, the GUI provides visual interaction, and applications use these components to implement functions.

How to check the warehouse address of git How to check the warehouse address of git Apr 17, 2025 pm 01:54 PM

To view the Git repository address, perform the following steps: 1. Open the command line and navigate to the repository directory; 2. Run the "git remote -v" command; 3. View the repository name in the output and its corresponding address.

vscode Previous Next Shortcut Key vscode Previous Next Shortcut Key Apr 15, 2025 pm 10:51 PM

VS Code One-step/Next step shortcut key usage: One-step (backward): Windows/Linux: Ctrl ←; macOS: Cmd ←Next step (forward): Windows/Linux: Ctrl →; macOS: Cmd →

How to run java code in notepad How to run java code in notepad Apr 16, 2025 pm 07:39 PM

Although Notepad cannot run Java code directly, it can be achieved by using other tools: using the command line compiler (javac) to generate a bytecode file (filename.class). Use the Java interpreter (java) to interpret bytecode, execute the code, and output the result.

How to run sublime after writing the code How to run sublime after writing the code Apr 16, 2025 am 08:51 AM

There are six ways to run code in Sublime: through hotkeys, menus, build systems, command lines, set default build systems, and custom build commands, and run individual files/projects by right-clicking on projects/files. The build system availability depends on the installation of Sublime Text.

What is the main purpose of Linux? What is the main purpose of Linux? Apr 16, 2025 am 12:19 AM

The main uses of Linux include: 1. Server operating system, 2. Embedded system, 3. Desktop operating system, 4. Development and testing environment. Linux excels in these areas, providing stability, security and efficient development tools.

laravel installation code laravel installation code Apr 18, 2025 pm 12:30 PM

To install Laravel, follow these steps in sequence: Install Composer (for macOS/Linux and Windows) Install Laravel Installer Create a new project Start Service Access Application (URL: http://127.0.0.1:8000) Set up the database connection (if required)

git software installation git software installation Apr 17, 2025 am 11:57 AM

Installing Git software includes the following steps: Download the installation package and run the installation package to verify the installation configuration Git installation Git Bash (Windows only)

See all articles