linux生产者消费者代码
时间: 2023-04-25 14:05:17 浏览: 125
生产者消费者 Linux代码
生产者消费者问题是一个经典的多线程问题,可以使用 Linux 中的 pthread 库来实现。下面是一个简单的生产者消费者代码示例:
```
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 16
#define OVER (-1)
int buffer[BUFFER_SIZE];
int add = 0;
int rem = 0;
int num = 0;
pthread_mutex_t mutex;
pthread_cond_t wait_empty;
pthread_cond_t wait_full;
void *producer(void *data) {
int i;
for (i = 1; i <= 50; i++) {
pthread_mutex_lock(&mutex);
while (num == BUFFER_SIZE) {
pthread_cond_wait(&wait_empty, &mutex);
}
buffer[add] = i;
add = (add + 1) % BUFFER_SIZE;
num++;
pthread_cond_signal(&wait_full);
pthread_mutex_unlock(&mutex);
}
pthread_mutex_lock(&mutex);
while (num == BUFFER_SIZE) {
pthread_cond_wait(&wait_empty, &mutex);
}
buffer[add] = OVER;
add = (add + 1) % BUFFER_SIZE;
num++;
pthread_cond_signal(&wait_full);
pthread_mutex_unlock(&mutex);
return NULL;
}
void *consumer(void *data) {
int i;
while (1) {
pthread_mutex_lock(&mutex);
while (num == 0) {
pthread_cond_wait(&wait_full, &mutex);
}
i = buffer[rem];
rem = (rem + 1) % BUFFER_SIZE;
num--;
pthread_cond_signal(&wait_empty);
pthread_mutex_unlock(&mutex);
if (i == OVER) {
break;
}
printf("%d\n", i);
}
return NULL;
}
int main() {
pthread_t th_a, th_b;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&wait_empty, NULL);
pthread_cond_init(&wait_full, NULL);
pthread_create(&th_a, NULL, producer, 0);
pthread_create(&th_b, NULL, consumer, 0);
pthread_join(th_a, NULL);
pthread_join(th_b, NULL);
pthread_cond_destroy(&wait_empty);
pthread_cond_destroy(&wait_full);
pthread这是一个简单的生产者消费者问题的 C 程序示例,使用了 Linux 中的 pthread 库来实现多线程。代码中定义了一个缓冲区 buffer,生产者线程将数据放入缓冲区,消费者线程从缓冲区中取出数据。使用了互斥锁和条件变量来保证线程间的同步和通信。
阅读全文