I am trying to run a program where one thread takes data from standart input and than and the other gives it on a standart output, nothing too complicated, but when I run my program with /.filename < test.in > test.out it doesnt do anything. When I compliled it by using gcc -pthread filename.c -o filename -W -Wall, no errors or warnings seems to accour. Can someone explain? Also in file test.out nothing is displayed and in test.in is a simple sentence. This is the program
#define V 300
pthread_cond_t cond;
pthread_mutex_t mutex;
char a[300];
int p = 0;
int w = 0;
void *thread1() {
while(1){
pthread_mutex_lock(&mutex);
printf("thread1");
while(p >0){
pthread_cond_wait(&cond, &mutex);
}
p = fread(a, sizeof(char), V ,stdin);
if(p == 0){
pthread_exit(NULL);
}
if(p <= V){
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
}
}
void *thread2() {
while(1){
pthread_mutex_lock(&mutex);
printf("thread2");
while(w >0){
pthread_cond_wait(&cond, &mutex);
}
w = fwrite(a, sizeof(char),p, stdout);
if(w == 0){
pthread_exit(NULL);
}
if(w <= V ){
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
}
}
int main (void) {
printf("main/n");
fflush(stdout);
pthread_t t1, t2;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init (&cond, NULL);
pthread_create(&t1, NULL, vlakno1, NULL);
pthread_create(&t2, NULL, vlakno2, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
You have the obvious typo in your
printf("main/n");rather thanprintf("main\n");(or justputs("main");) but this is a detail and not thre reason why your program will never finishin vlakno1 you create a deadlock doing :
because you do not unlock the mutext, must be
you have the same problem in vlakno2 :
must be
The following is also strange :
even it is not impossible, it is difficult to have a write on stdou without success. So the alone chance for you to go out that loop is to have
poc_precitanychvaluing 0Additional remark, you
#define V 300but you dochar a[300];while you use V elsewhere. Better to dochar a[V];or to usesizeof(a)elsewhere without defining VExamples of execution after the changes :
there is nothing to read so
poc_precitanychvalues 0 and the two thread finishes, but