#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
char buf[]="qwertyuiioo";
sem_t print_lock; // 打印锁
sem_t reverse_lock; // 倒置锁
void *print_thread(void *arg)
{
sem_wait(&print_lock); // 等待打印锁
printf("%s\n",buf);
sem_post(&reverse_lock); // 解锁倒置锁
pthread_exit(NULL);
}
void *reverse_thread(void *arg)
{
int len=strlen(buf);
sem_wait(&reverse_lock); // 等待倒置锁
for(int i=0;i<len/2;i++)
{
int temp = buf[i];
buf[i] = buf[len-i-1];
buf[len-i-1] = temp;
}
printf("%s\n",buf);
sem_post(&print_lock); // 解锁打印锁
pthread_exit(NULL);
}
int main()
{
sem_init(&print_lock, 0, 1);
sem_init(&reverse_lock, 0, 0);
pthread_t print_tid, reverse_tid;
pthread_create(&print_tid, NULL, print_thread, NULL);
pthread_create(&reverse_tid, NULL, reverse_thread, NULL);
pthread_join(print_tid, NULL);
pthread_join(reverse_tid, NULL);
sem_destroy(&print_lock);
sem_destroy(&reverse_lock);
return 0;
}
3月4日作业
最新推荐文章于 2024-07-19 17:37:28 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)