#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <semaphore.h>
char a;
char b;
sem_t sem;//信号量
int flag;//标志位
void *xc(void *arg)
{
getchar();//接收"\n"
printf("请输入B:");
scanf("%c", &b);
while (1)
{
sem_wait(&sem);//等待主线程释放资源
if (flag == 1)
{
printf("a=%c\n", a);
}
flag = 0;
}
}
int main(int argc, char const *argv[])
{
pthread_t tid;
pthread_create(&tid, NULL, xc, NULL);
sem_init(&sem, 0, 0);
printf("请输入A:");
scanf("%c", &a);
flag = 1;
while (1)
{
if (flag == 0)//开始b为空,不打印
{
printf("b=%c\n", b);
flag = 1;
}
sem_post(&sem);//为子线程申请资源
sleep(1);
}
pthread_join(tid, NULL);
return 0;
}