#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
int count = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t notfull = PTHREAD_COND_INITIALIZER;
pthread_cond_t notempty = PTHREAD_COND_INITIALIZER;
void insert(int item) {
pthread_mutex_lock(&mutex);
while (count == BUFFER_SIZE) {
pthread_cond_wait(¬full, &mutex);
}
buffer[in] = item;
in = (in + 1) % BUFFER_SIZE;
++count;
pthread_cond_signal(¬empty);
pthread_mutex_unlock(&mutex);
}
int remove() {
int item;
pthread_mutex_lock(&mutex);
while (count == 0) {
pthread_cond_wait(¬empty, &mutex);
}
item = buffer[out];
out = (out + 1) % BUFFER_SIZE;
--count;
pthread_cond_signal(¬full);
pthread_mutex_unlock(&mutex);
return item;
}
void* producer(void* arg) {
int i;
for (i = 0; i < 10; ++i) {
insert(i);
printf("Produced: %d\n", i);
sleep(1);
}
return NULL;
}
void* consumer(void* arg) {
int val;
while (1) {
val = remove();
printf("Consumed: %d\n", val);
sleep(1);
}
return NULL;
}
int main() {
pthread_t ptid, ctid;
pthread_create(&ptid, NULL, producer, NULL);
pthread_create(&ctid, NULL, consumer, NULL);
pthread_join(ptid, NULL);
pthread_join(ctid, NULL);
return 0;
}
这段代码实现了一个简单的生产者-消费者模型,其中包含了一个有限缓冲区。它使用了条件变量来同步生产者和消费者,确保在缓冲区为空或为满时不会消耗或生产数据,从而避免了竞态条件。这个例子教会了如何在Linux环境下使用C语言编写并发程序。
FR:徐海涛(hunk Xu)