简体   繁体   中英

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. 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(&thread_id, NULL);
printf("Ingresa un numero: ");
scanf("%d", &t);

By the way, you don't need to call pthread_exit in your main().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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