#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define MAX_NUM 20
int count = 1; // 全局计数,从1开始
pthread_mutex_t mutex; // 互斥锁
pthread_cond_t cond; // 条件变量
// 线程A:打印奇数
void *thread_a(void *arg) {
while (1) {
pthread_mutex_lock(&mutex); // 加锁
// 若当前是偶数,等待线程B打印后唤醒
while (count % 2 == 0) {
pthread_cond_wait(&cond, &mutex);
}
// 检查是否超过最大值,退出
if (count > MAX_NUM) {
pthread_mutex_unlock(&mutex);
break;
}
// 打印奇数
printf("线程A: %d\n", count);
count++; // 计数自增
pthread_cond_signal(&cond); // 唤醒线程B
pthread_mutex_unlock(&mutex); // 解锁
}
return NULL;
}
// 线程B:打印偶数
void *thread_b(void *arg) {
while (1) {
pthread_mutex_lock(&mutex); // 加锁
// 若当前是奇数,等待线程A打印后唤醒
while (count % 2 != 0) {
pthread_cond_wait(&cond, &mutex);
}
// 检查是否超过最大值,退出
if (count > MAX_NUM) {
pthread_mutex_unlock(&mutex);
break;
}
// 打印偶数
printf("线程B: %d\n", count);
count++; // 计数自增
pthread_cond_signal(&cond); // 唤醒线程A
pthread_mutex_unlock(&mutex); // 解锁
}
return NULL;
}
int main() {
pthread_t tid_a, tid_b;
// 初始化互斥锁和条件变量
if (pthread_mutex_init(&mutex, NULL) != 0) {
perror("mutex init failed");
exit(EXIT_FAILURE);
}
if (pthread_cond_init(&cond, NULL) != 0) {
perror("cond init failed");
pthread_mutex_destroy(&mutex);
exit(EXIT_FAILURE);
}
// 创建线程
if (pthread_create(&tid_a, NULL, thread_a, NULL) != 0) {
perror("create thread a failed");
goto cleanup;
}
if (pthread_create(&tid_b, NULL, thread_b, NULL) != 0) {
perror("create thread b failed");
pthread_cancel(tid_a);
goto cleanup;
}
// 等待线程结束
pthread_join(tid_a, NULL);
pthread_join(tid_b, NULL);
cleanup:
// 销毁互斥锁和条件变量
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}