我必须从 Dispatched Thread
获取输入并对其进行一些计算。我在使用 stdio.h
的 scanf()
从线程获取输入时遇到问题。
控制台不提示输入。这是我的代码
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<pthread.h>
#include<stdio.h>
void* square(){
puts("\nfirst line of child\n");
int input,i=0;
fflush(stdin);
scanf("%d",&input);
do{
scanf("%d",&i);
}while(i!=0);
printf("\ninput is %d\n",input);
puts("\nlast line of child\n");
pthread_exit(NULL);
}
int main(void){
puts("\nI'm Parent & I'm Starting\n");
pthread_t thread;
pthread_attr_t pthread_attr;
pthread_attr_init(&pthread_attr);
pthread_attr_setdetachstate(&pthread_attr,PTHREAD_CREATE_DETACHED);
pid_t tid = pthread_create(&thread,& pthread_attr,square,NULL);
puts("\nI'm Parent & I'm going to exit\n");
return EXIT_SUCCESS;
}
我试过 fflush(stdin)
来刷新输入流,但这也没有帮助我。
我得到的是(这不执行输入行)。
I'm Parent & I'm Starting
I'm Parent & I'm going to exit
first line of child
first line of child`
最佳答案
删除:
fflush(stdin);
并对 main 进行以下更改:
pthread_create(&thread,&pthread_attr,square,NULL);
(void)pthread_join(thread, NULL); // <--- will wait for thread
然后它可能会按您预期的那样工作。
另一种方法是使用 pthread_exit() 终止主线程,然后让子线程继续,但那将是一个非常糟糕的设计。它实际上使 pid 在我的系统上“失效”,即使子线程似乎继续执行。由于其他原因,它也是一个糟糕的设计。
关于c - scanf() 在线程中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46487795/