c - Not able to find the bug in my multithreading program? -
i have implemented simple multithreading program, producer access global variable , fills it, after consumner prints it.
i have written main
#include<stdio.h> #include<stdlib.h> #include<pthread.h> void *prod(void); void *cons(void); unsigned int my_var = 0; pthread_mutex_t mut = pthread_mutex_initializer; int main() { pthread_t th1, th2; int status; status = pthread_create(&th1, null, (void*)prod, null); if(status) { printf("error creating thread 1 : %d\n", status); exit(-1); } status = pthread_create(&th2, null, (void*)cons, null); if(status) { printf("error creating thread 2 : %d\n", status); exit(-1); } pthread_join(th1, null); pthread_join(th2, null); return 0; }
my producer function goes :
void *prod(void) { while(1) { pthread_mutex_unlock(&mut); printf("enter value : "); scanf("%d", &my_var); } }
consumer function :
void *cons(void) { while(1) { printf("the value entered %d\n", my_var); pthread_mutex_lock(&mut); } }
this program runs exact output pattern different, :
enter value : value entered 0 value entered 0 45 enter value : value entered 45 85 enter value : value entered 85 12 enter value : value entered 12 67 enter value : value entered 67 49 enter value : value entered 49
i finding difficult rectify logic new threading concept. please me out in resolving issue.
my expected output :
enter value : 45 value entered 45 .........................................
after answer's , guidelines use mutex_cond_var. used them in function :
void *prod(void) { while(1) { printf("enter value : "); scanf("%d", &my_var); pthread_cond_signal(&condition_var1); pthread_mutex_unlock(&mut); } } void *cons(void) { while(1) { pthread_mutex_lock(&mut); pthread_cond_wait( &condition_var1, &mut ); printf("the value entered %d\n", my_var); } }
resulted output :
enter value : 78 enter value : value entered 78 86 enter value : 15 enter value : value entered 15 35 enter value : 86 enter value : value entered 86 12 enter value : 65 enter value : value entered 65 78 enter value : 65 enter value : value entered 65 12 enter value : 35 enter value : value entered 35
please guide me in cleaning code expected output.
i suggest use conditional variable such cases.
https://computing.llnl.gov/tutorials/pthreads/#convaroverview
this way more efficient task. consumer should wait cond variable. when producer new data, notify condition variable , consumer wake job data.
the link above has pretty explanation, if have questions, welcome
Comments
Post a Comment