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 }
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 }
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 }
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)!