#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#define BUF_SIZE 10
int buf[BUF_SIZE];
int in_idx = 0; // 写入索引
int out_idx = 0; // 读取索引
int count = 0; // 当前数据个数
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 互斥锁
pthread_cond_t cond = PTHREAD_COND_INITIALIZER; // 条件变量
// 线程A:生成随机数
void *thread_a(void *arg) {
srand(time(NULL)); // 初始化随机数种子
while (1) {
pthread_mutex_lock(&mutex);
if (count < BUF_SIZE) { // 数组未满
int num = rand() % 100 + 1; // 生成1-100的随机数
buf[in_idx] = num;
in_idx = (in_idx + 1) % BUF_SIZE;
count++;
printf("线程A写入:%d,当前计数:%d\n", num, count);
pthread_cond_signal(&cond); // 唤醒线程B
} else {
printf("线程A:缓冲区满,跳过写入\n");
}
pthread_mutex_unlock(&mutex);
sleep(1); // 每1秒生成一个
}
return NULL;
}
// 线程B:读取并打印
void *thread_b(void *arg) {
while (1) {
pthread_mutex_lock(&mutex);
// 若缓冲区为空,等待条件变量(自动释放锁,被唤醒时重新加锁)
while (count == 0) {
printf("线程B:缓冲区空,等待数据...\n");
pthread_cond_wait(&cond, &mutex);
}
// 读取数据
int data = buf[out_idx];
out_idx = (out_idx + 1) % BUF_SIZE;
count--;
printf("线程B读取:%d,剩余计数:%d\n", data, count);
pthread_mutex_unlock(&mutex);
usleep(500000); // 休眠500ms
}
return NULL;
}
int main() {
pthread_t tid_a, tid_b;
// 创建线程
if (pthread_create(&tid_a, NULL, thread_a, NULL) != 0) {
perror("pthread_create thread_a failed");
return -1;
}
if (pthread_create(&tid_b, NULL, thread_b, NULL) != 0) {
perror("pthread_create thread_b failed");
return -1;
}
// 等待线程(实际中可加信号处理退出,此处简化为无限循环)
pthread_join(tid_a, NULL);
pthread_join(tid_b, NULL);
// 清理资源(实际中需在退出时调用)
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}