生产者消费者模型和读者写者模型使我们常见的关于线程同步与互斥有关的模型,它们的实现对理解线程同步互斥有很好的帮助。
生产者消费者模型
如上图,生产者生产一个产品并放到仓库中,消费者从仓库中取产品,生产和消费者两个动作是互斥的,而生产者和生产者,消费者和消费者之间是同步的。
具体代码实现如下:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#define CONSUMERS 2
#define PRODUCERS 2
typedef struct msg{
struct msg* next;
int num;
}msg;
struct msg* head = NULL;
pthread_cond_t cond;
pthread_mutex_t mutex;
pthread_t threads[CONSUMERS + PRODUCERS];
void* consumer(void* p){
free(p);
for(;;){
}
int num = *(int *)p;
free(p);
struct msg* mp;
for(;;){
pthread_mutex_lock(&mutex);
while(head == NULL){
printf("%d begin wait a condition\n", num);
pthread_cond_wait(&cond, &mutex);
}
printf("%d end wait a condition\n", num);
printf(