pthread_cond_wait & pthread_cond_signal

struct worker_thread_info
{
pthread_t id;
bool_t is_free;
pthread_mutex_t task_mutex;
pthread_cond_t cond_var;
};

 

/* Initialize worker thread related structures/variales */
w_thread.id = ERROR;
w_thread.is_free = TRUE;
pthread_mutex_init (&w_thread.task_mutex, NULL);
pthread_cond_init (&w_thread.cond_var, NULL);

ret = pthread_create (&master->w_thread.id, NULL,
init_worker_thread, NULL);
if (ret != OK)
{
return ERROR;
}

===================
init_worker_thread ()
{
/* Main Loop for worker thread */
while (TRUE)
{
pthread_mutex_lock (&w_thread.task_mutex);
w_thread.is_free = TRUE;

/* Block on cond_var & release mutex */
/* Wait for signal from main thread */
pthread_cond_wait (&w_thread.cond_var,
&w_thread.task_mutex);
w_thread.is_free = FALSE;
pthread_mutex_unlock (&w_thread.task_mutex);

process_request ();
}
}
===================

/* Get a local copy */
pthread_mutex_lock (&w_thread.task_mutex);
is_wt_free = w_thread.is_free;
pthread_mutex_unlock (&w_thread.task_mutex);

/* If worker thread is free handover to it */
if (is_wt_free)
{
/* Send signal to worker.. you have a job to do now */
pthread_mutex_lock (&w_thread.task_mutex);
pthread_cond_signal (&w_thread.cond_var);
pthread_mutex_unlock (&w_thread.task_mutex);
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s