Waseem Ahmad Naeem
Waseem Ahmad Naeem

Reputation: 890

scanf() is not working in Thread

I've to get input from Dispatched Thread and do some calculations on it. I'm facing issue while getting input from thread using scanf() of stdio.h. console does not prompt for the input. Here is my code

#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;
}

I tried fflush(stdin) to flush input stream but this also failed to help me.

Out I'm getting is (this does not execute the line of input).

I'm Parent & I'm Starting


I'm Parent & I'm going to exit


first line of child

first line of child`

Upvotes: 0

Views: 2099

Answers (1)

user1048576
user1048576

Reputation: 330

Remove the:

    fflush(stdin);

and make these changes to main:

    pthread_create(&thread,&pthread_attr,square,NULL);
    (void)pthread_join(thread, NULL); // <--- will wait for thread

Then it will probably work as you expect.

Another approach would be to terminate the main thread with pthread_exit() and then let the child continue, but that would be a really bad design. It actually leaves the pid as "defunct" on my system even though the child thread seems to continue to execute. It is a bad design for other reasons as well.

Upvotes: 3

Related Questions