写出实现消费者和生产者的具有特定索引的多线程的C语言代码
时间: 2024-05-13 13:15:23 浏览: 97
C语言实现多个生产者和消费者.doc
好的,让我来为您提供一个具有特定索引的多线程的C语言代码:
```c
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE]; // 共享缓冲区
sem_t empty; // 生产者信号量
sem_t full; // 消费者信号量
pthread_mutex_t mutex; // 互斥锁
// 生产者线程函数
void *producer(void *param) {
int index = *(int *)param;
int i, item;
free(param);
while (1) {
item = rand() % 1000;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
for (i = 0; i < BUFFER_SIZE; i++) {
if (buffer[i] == -1) {
buffer[i] = item;
printf("Producer %d: item %d added at index %d\n", index, item, i);
break;
}
}
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
// 消费者线程函数
void *consumer(void *param) {
int index = *(int *)param;
int i, item;
free(param);
while (1) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
for (i = 0; i < BUFFER_SIZE; i++) {
if (buffer[i] != -1) {
item = buffer[i];
buffer[i] = -1;
printf("Consumer %d: item %d removed from index %d\n", index, item, i);
break;
}
}
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
int main() {
int i, *index;
pthread_t producer_threads[5], consumer_threads[3];
// 初始化缓冲区
for (i = 0; i < BUFFER_SIZE; i++) {
buffer[i] = -1;
}
// 初始化信号量和互斥锁
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, NULL);
// 创建5个生产者线程
for (i = 0; i < 5; i++) {
index = (int *)malloc(sizeof(int));
*index = i;
pthread_create(&producer_threads[i], NULL, producer, (void *)index);
}
// 创建3个消费者线程
for (i = 0; i < 3; i++) {
index = (int *)malloc(sizeof(int));
*index = i;
pthread_create(&consumer_threads[i], NULL, consumer, (void *)index);
}
// 等待线程结束
for (i = 0; i < 5; i++) {
pthread_join(producer_threads[i], NULL);
}
for (i = 0; i < 3; i++) {
pthread_join(consumer_threads[i], NULL);
}
// 销毁信号量和互斥锁
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
return 0;
}
```
这是一个基于缓冲区的生产者和消费者模型,使用了互斥锁和信号量来保证线程同步和互斥。其中,生产者线程随机生成一个数字,并将其放入共享缓冲区中,而消费者线程从共享缓冲区中取出一个数字。每次只有一个生产者或消费者能够访问缓冲区,保证了线程安全。在代码中,索引值被分配给每个线程,以便将输出正确地标识到特定的线程上。
阅读全文