i experiencing problems thread synchronization using pthread conditional variable. have 1 thread parses messages extracting values , thread increments variables using extracted values. used pthread conditional variable synchronize these 2 threads. first thread looks snippet below:
if(parse_ok){ pthread_mutex_lock(&q_mutex); q = extract_value(); q_changed = true; printf("...awake\n"); pthread_cond_signal(&q_cond_var); pthread_mutex_unlock(&q_mutex); }
the worker thread looks snippet below:
while(true){ pthread_mutex_lock(&q_mutex); if( !q_changed ){ std::cout<<"waiting..!"<<std::endl; pthread_cond_wait(&q_cond_var, &q_mutex); } if(q_changed){ q_changed = false; _actual_q += q; _total_q += q; _quant_q += q/_fixed_quantity; } pthread_mutex_unlock(&q_mutex); }//end of while true
this code works correctly of time. happens, when receive lot of messages, 1 after other, sleeping thread skips awakening. may need semaphore block receiving thread until working thread completes work? how? in advance.
the way code written, there's no guarantee second worker thread process new input every time first thread signals it. can extend use q_changed
variable, however, ensure happens.
change first thread this:
if(parse_ok){ pthread_mutex_lock(&q_mutex); while (q_changed) // wait in in loop pthread_cond_wait(&q_cond_var, &q_mutex); q = extract_value(); q_changed = true; pthread_cond_signal(&q_cond_var); pthread_mutex_unlock(&q_mutex); }
and change second, worker thread this:
while(true){ pthread_mutex_lock(&q_mutex); while( !q_changed ) // wait in loop pthread_cond_wait(&q_cond_var, &q_mutex); q_changed = false; _actual_q += q; _total_q += q; _quant_q += q/_fixed_quantity; pthread_cond_signal(&q_cond_var); pthread_mutex_unlock(&q_mutex); }
Comments
Post a Comment