使用进程间条件变量,写一个多消费者,单生产者的多进程模型
时间: 2023-05-12 21:04:27 浏览: 64
可以使用 POSIX 标准库中的 pthread_cond_t 和 pthread_mutex_t 实现进程间条件变量。以下是一个多消费者,单生产者的多进程模型的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define BUFFER_SIZE 10
#define SHM_KEY 1234
typedef struct {
int buffer[BUFFER_SIZE];
pthread_mutex_t mutex;
int read_pos, write_pos;
pthread_cond_t not_empty;
pthread_cond_t not_full;
} shared_data;
shared_data *data;
void *producer(void *arg) {
int value = 0;
while (1) {
pthread_mutex_lock(&data->mutex);
while ((data->write_pos + 1) % BUFFER_SIZE == data->read_pos) {
pthread_cond_wait(&data->not_full, &data->mutex);
}
data->buffer[data->write_pos] = value;
data->write_pos++;
if (data->write_pos >= BUFFER_SIZE) {
data->write_pos = 0;
}
pthread_cond_signal(&data->not_empty);
pthread_mutex_unlock(&data->mutex);
value++;
sleep(1);
}
return NULL;
}
void *consumer(void *arg) {
int id = *(int *)arg;
while (1) {
pthread_mutex_lock(&data->mutex);
while (data->read_pos == data->write_pos) {
pthread_cond_wait(&data->not_empty, &data->mutex);
}
int value = data->buffer[data->read_pos];
data->read_pos++;
if (data->read_pos >= BUFFER_SIZE) {
data->read_pos = 0;
}
pthread_cond_signal(&data->not_full);
pthread_mutex_unlock(&data->mutex);
printf("Consumer %d: %d\n", id, value);
sleep(2);
}
return NULL;
}
int main() {
int shmid = shmget(SHM_KEY, sizeof(shared_data), 0666 | IPC_CREAT);
if (shmid == -1) {
perror("shmget");
exit(1);
}
data = shmat(shmid, NULL, 0);
if (data == (void *)-1) {
perror("shmat");
exit(1);
}
pthread_mutex_init(&data->mutex, NULL);
data->read_pos = 0;
data->write_pos = 0;
pthread_cond_init(&data->not_empty, NULL);
pthread_cond_init(&data->not_full, NULL);
pthread_t producer_thread;
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_t consumer_threads[3];
int ids[3] = {1, 2, 3};
for (int i = 0; i < 3; i++) {
pthread_create(&consumer_threads[i], NULL, consumer, &ids[i]);
}
pthread_join(producer_thread, NULL);
for (int i = 0; i < 3; i++) {
pthread_join(consumer_threads[i], NULL);
}
pthread_mutex_destroy(&data->mutex);
pthread_cond_destroy(&data->not_empty);
pthread_cond_destroy(&data->not_full);
shmdt(data);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
```
在这个示例代码中,我们使用了共享内存来存储生产者和消费者之间的数据。生产者线程不断地向缓冲区中写入数据,而消费者线程则不断地从缓冲区中读取数据。当缓冲区满时,生产者线程会等待条件变量 not_full,而当缓冲区为空时,消费者线程会等待条件变量 not_empty。这样可以保证生产者和消费者之间的同步。