生产者和消费者进程的同步与互斥 代码c++
时间: 2023-10-11 08:05:58 浏览: 127
生产者与消费者 进程的同步与互斥模拟
5星 · 资源好评率100%
关于生产者和消费者进程的同步与互斥的代码实现,以下是一个简单的示例:
```
#include <stdio.h>
#include <pthread.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int count = 0;
int in = 0, out = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_full = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_empty = PTHREAD_COND_INITIALIZER;
void *producer(void *arg){
int tid = *(int*)arg;
for (int i = 0; i < 100; i++){
pthread_mutex_lock(&mutex);
while (count == BUFFER_SIZE){ // 缓冲区已满,等待消费者消费
pthread_cond_wait(&cond_full, &mutex);
}
buffer[in] = rand() % 100;
printf("生产者%d生产了%d\n", tid, buffer[in]);
in = (in + 1) % BUFFER_SIZE;
count++;
pthread_cond_signal(&cond_empty); // 通知消费者可以消费了
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void *consumer(void *arg){
int tid = *(int*)arg;
for (int i = 0; i < 100; i++){
pthread_mutex_lock(&mutex);
while (count == 0){ // 缓冲区为空,等待生产者生产
pthread_cond_wait(&cond_empty, &mutex);
}
int data = buffer[out];
printf("消费者%d消费了%d\n", tid, data);
out = (out + 1) % BUFFER_SIZE;
count--;
pthread_cond_signal(&cond_full); // 通知生产者可以生产了
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(){
pthread_t p1, p2, c1, c2;
int id1 = 1, id2 = 2;
pthread_create(&p1, NULL, producer, &id1);
pthread_create(&p2, NULL, producer, &id2);
pthread_create(&c1, NULL, consumer, &id1);
pthread_create(&c2, NULL, consumer, &id2);
pthread_join(p1, NULL);
pthread_join(p2, NULL);
pthread_join(c1, NULL);
pthread_join(c2, NULL);
return 0;
}
```
在这个示例中,使用了互斥锁 `mutex` 和条件变量 `cond_full`、`cond_empty` 实现了生产者和消费者的同步与互斥。当生产者需要生产时,若缓冲区已满,则进入等待状态,等待消费者消费;当消费者需要消费时,若缓冲区为空,则进入等待状态,等待生产者生产。生产者和消费者之间通过条件变量进行通知,以达到同步与互斥的效果。
阅读全文