在一个子线程中初始化结构体变量,在另一个子线程中打印结构体变量中元素
作者:互联网
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#include <string.h>
#include <stdlib.h>
struct data_t{
char name[20];
int id;
int score;
};
struct data_t stu;
sem_t read_sem;
sem_t write_sem;
void *input_thread(void *arg)
{
while(1){
sem_wait(&write_sem);
memset(&stu, 0, sizeof(stu));
printf("please input name id score\n");
//scanf("%s,%d,%d\n", stu.name, &(stu.id), &(stu.score));//错误代码
scanf("%s%d%d", stu.name, &(stu.id), &(stu.score));//""中不能带有,号。不能带\n
fflush(stdin);//刷新缓存
if(strncmp(stu.name, "quit", 4) == 0){
exit(0);
}
sem_post(&read_sem);
}
}
void *output_thread(void *arg)
{
while(1){
sem_wait(&read_sem);
printf("name:%s\n", stu.name);
printf("id:%d\n", stu.id);
printf("score:%d\n", stu.score);
sem_post(&write_sem);
}
}
int main(int argc, const char *argv[])
{
sem_init(&read_sem,0, 0);
sem_init(&write_sem,0 ,1);
int ret1;
int ret2;
pthread_t tid1;
pthread_t tid2;
ret1 = pthread_create(&tid1, NULL, input_thread, NULL);
ret2 = pthread_create(&tid2, NULL, output_thread, NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
标签:初始化,变量,int,stu,线程,sem,NULL,id,name 来源: https://www.cnblogs.com/thismajor/p/16197166.html