c - scanf() 在线程中不起作用

标签 c multithreading ubuntu unix

我必须从 Dispatched Thread 获取输入并对其进行一些计算。我在使用 stdio.hscanf() 从线程获取输入时遇到问题。 控制台不提示输入。这是我的代码

#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/

相关文章:

c - 如何通过网络套接字可移植地发送 C 结构?

multithreading - Crystal 将线程池背后的想法转换为 Fibers/spawn

Java 线程创建

c - 如何区分同一 HTTPS 流量中的不同类型的数据包?

add 函数中的 C trie 内存泄漏

c - 为什么当我也打印行数时,行数显示为 0,但当它只是行数时却工作正常

c# - 与使用 Interlocked 类相比,使用 volatile 关键字有什么优势吗?

ubuntu - CMake 找不到包

windows - Ubuntu 启动菜单

php - 生成 HTML 正文和 PDF 附件时的电子邮件问题