简体   繁体   English

c-scanf中断,并且printf在线程中

[英]c - scanf interrupted, and printf in thread

I have a simple thread that prints numbers and the problem is that thread is printed on scanf. 我有一个打印数字的简单线程,问题是该线程打印在scanf上。 Something like that. 这样的事情。

input> DATAOFTHREAD

but I want to print the result something like that 但我想打印结果像这样

DATAOFTHREAD
input>

it is possible? 有可能的? what function should I use? 我应该使用什么功能? This is my code: 这是我的代码:

#include <stdio.h>
#include <pthread.h> 

void *connection_handler(void* data) {
    int i = (int)data;
    for(i=0;i<5;i++) {
        printf("%d", i);
        fflush(stdout);

    }

    pthread_exit(NULL);
}

int main()
{   
    int t;
    int x;
    int rc;
    pthread_t thread_id;
    rc = pthread_create(&thread_id, NULL, connection_handler, (void *)x);
    if(rc) {
        printf("Error en pthread()\n");
        return 1;
    }
    printf("Ingresa un numero: ");
    scanf("%d", &t);

    printf("%d\n", t);

    pthread_exit(NULL);

    return 0;

} }

Thanks 谢谢

You can call pthread_join so that you do scanf only after your thread has finished: 您可以调用pthread_join,以便仅在线程完成后才执行scanf:

pthread_join(&thread_id, NULL);
printf("Ingresa un numero: ");
scanf("%d", &t);

By the way, you don't need to call pthread_exit in your main(). 顺便说一句,您不需要在main()中调用pthread_exit。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM