qfedu-linux-advanced-level/day7/homework/h1_2.c

85 lines
2.1 KiB
C
Raw Normal View History

#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t condition;
int max_number;
int current_number;
void *print_odd(void *arg)
{
while (1)
{
pthread_mutex_lock(&mutex);
while (current_number % 2 == 0)
{ // 等待偶数线程通知
pthread_cond_wait(&condition, &mutex);
}
if (current_number > max_number)
{ // 达到最大值时退出
pthread_mutex_unlock(&mutex);
break;
}
printf("%d", current_number);
if (current_number != max_number)
printf("");
else if (current_number == max_number)
printf("\n");
fflush(stdout);
current_number++;
pthread_cond_signal(&condition); // 通知偶数线程
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void *print_even(void *arg)
{
while (1)
{
pthread_mutex_lock(&mutex);
while (current_number % 2 != 0)
{ // 等待奇数线程通知
pthread_cond_wait(&condition, &mutex);
}
if (current_number > max_number)
{ // 达到最大值时退出
pthread_mutex_unlock(&mutex);
break;
}
printf("%d", current_number);
if (current_number != max_number)
printf("");
else if (current_number == max_number)
printf("\n");
fflush(stdout);
current_number++;
pthread_cond_signal(&condition); // 通知奇数线程
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main()
{
printf("请输入指定的最大值: ");
scanf("%d", &max_number);
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&condition, NULL);
current_number = 1;
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(&condition);
return 0;
}