I am new to threads. I want to make two threads xthread
prints 'X'; and ythread
prints 'Z'; continuously until the user inserts 'C'
or 'c'
at stdin
. I have made use of select to check if there is any userinput. If there is a userinput I use scanf
to obtain it in read
and do the comparison.
I have kept read
as global. [Is there any other way of sharing non-global data between threads? ] . I have assumed that, when the user enters 'c'
at stdin the thread which is currently running reads it and stores it in read and breaks out
. I have used the flag read_input
to indicate to other threads that input has already been taken and you don't need to take userinput again.
Problem:
user enters 'c'
xthread exits [or ythread]
However, ythread still keeps looping and exits only after i enter 'c'
again.
[My assumption is it has read the previous value of read
and is still using the same value for comparing]
What have I done wrong?
#include<stdio.h>
#include<sys/select.h>
#include<pthread.h>
static unsigned int i =0;
char read;
int read_input = 0;
void* print_fn(void* arg)
{
int fd = fileno(stdin);
struct timeval tv = {0,0};
fd_set fdset;
int s;
char *buffer = NULL;
unsigned int len;
while(1)
{
struct timespec t = {0,433300000};
const struct timespec * tp = &t;
nanosleep(tp,&t);
printf("\nValue of read is %d",read);
//sleep(1);
FD_ZERO(&fdset);
FD_SET(fd, &fdset);
printf("\n%p prints %c and i is %d",pthread_self(),*((char*)arg),i++);
if((s = select(fd+1, &fdset, NULL, NULL, &tv)) == 1)
{
printf("\nValue of s is %d",s);
if(!read_input)
scanf("%c",&read);
fflush(stdin);
printf("\nValue of read is %d",read);
printf("\nChecked for %d or % d",'C','c');
if(read == 'C' || read == 'c')
{
read_input = 1;
break;
}
}
printf("\nHere");
}
printf("\nI, %p survived while(1)",pthread_self());
return NULL;
}
int main()
{
pthread_t xthread,ythread,checkThread;
char c1 = 'X', c2 = 'Z';
pthread_create(&xthread,NULL,print_fn,&c1);
pthread_create(&ythread,NULL,print_fn,&c2);
pthread_join(xthread,NULL);
pthread_join(ythread,NULL);
return 0;
}
If there is a better way of taking userinput,please let me know.
I don't know if using pthread_cond_t
would solve my issue. I don't find the necessity to use a mutex. [Correct me if I am wrong]