生产者和消费者进程的同步与互斥 c语言代码
时间: 2023-10-11 14:06:16 浏览: 106
生产者与消费者 进程的同步与互斥模拟
5星 · 资源好评率100%
对于您的问题,我可以给出以下的同步与互斥 c语言代码:
#include <stdio.h>
#include <pthread.h>
int buffer = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_prod = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_cons = PTHREAD_COND_INITIALIZER;
void *producer(void *arg) {
for(int i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex);
while(buffer != 0) {
pthread_cond_wait(&cond_prod, &mutex);
}
buffer = 1;
printf("Producer produced %d\n", buffer);
pthread_cond_signal(&cond_cons);
pthread_mutex_unlock(&mutex);
}
}
void *consumer(void *arg) {
for(int i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex);
while(buffer == 0) {
pthread_cond_wait(&cond_cons, &mutex);
}
buffer = 0;
printf("Consumer consumed %d\n", buffer);
pthread_cond_signal(&cond_prod);
pthread_mutex_unlock(&mutex);
}
}
int main() {
pthread_t prod_thread, cons_thread;
pthread_create(&prod_thread, NULL, producer, NULL);
pthread_create(&cons_thread, NULL, consumer, NULL);
pthread_join(prod_thread, NULL);
pthread_join(cons_thread, NULL);
return 0;
}
以上代码中,使用了互斥锁 pthread_mutex_t和条件变量pthread_cond_t,生产者和消费者在互相等待对方完成任务的情况下,通过条件变量的信号发送与等待调用,完成同步和互斥的功能。
阅读全文