一、题目要求
编写一个C语言程序,实现多线程并发打印奇偶数。要求使用两个线程,一个线程打印奇数,另一个线程打印偶数,打印范围为1到100。要求奇数线程先打印,偶数线程后打印,且要保证线程按次序交替进行。
请根据要求完成begin、end间完成代码,不要改变代码中其他部分。
二、程序代码
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>// 定义互斥锁和条件变量
pthread_mutex_t mutex;
pthread_cond_t odd_cond;
pthread_cond_t even_cond;int number = 1;
int MAX_NUMBER = 100;// 奇数线程函数
void* print_odd(void* arg) {while (number < MAX_NUMBER) {// 上锁pthread_mutex_lock(&mutex);// 当前是偶数,等待奇数线程打印if (number % 2 == 0) {///Begin///pthread_exit(NULL);End }// 打印奇数printf("奇数线程为:%d\n", number++);// 发送信号给偶数线程pthread_cond_signal(&even_cond);// 解锁pthread_mutex_unlock(&mutex);}pthread_exit(NULL);
}// 偶数线程函数
void* print_even(void* arg) {while (number < MAX_NUMBER) {// 上锁pthread_mutex_lock(&mutex);// 当前是奇数,等待偶数线程打印if (number % 2 == 1) {///Begin///pthread_exit(NULL);End }// 打印偶数printf("偶数线程为:%d\n", number++);// 发送信号给奇数线程pthread_cond_signal(&odd_cond);// 解锁pthread_mutex_unlock(&mutex);}pthread_exit(NULL);
}int main() {// 初始化互斥锁和条件变量pthread_mutex_init(&mutex, NULL);pthread_cond_init(&odd_cond, NULL);pthread_cond_init(&even_cond, NULL);// 创建奇数线程和偶数线程pthread_t odd_thread, even_thread;pthread_create(&odd_thread, NULL, print_odd, NULL);pthread_create(&even_thread, NULL, print_even, NULL);// 等待线程执行结束pthread_join(odd_thread, NULL);pthread_join(even_thread, NULL);// 销毁互斥锁和条件变量pthread_mutex_destroy(&mutex);pthread_cond_destroy(&odd_cond);pthread_cond_destroy(&even_cond);return 0;
}
三、在DEV C++测试运行