Howard Shane
Howard Shane

Reputation: 956

Linux, C: threads synch

My application has multiple threads created by pthread_create. Now, all other threads need to wait until a particular thread change a state, for example: one status thread is monitoring system status, if it is ready, then tell other threads to start doing their work. How do I implement this in Linux with C?

===sudo code===

static int status = 0;
static pthread_mutex_t status_mutex = PTHREAD_MUTEX_INITIALIZER;

void good_to_go( void )
{
        pthread_mutex_lock( &status_mutex );
        status = 1;
        pthread_mutex_unlock( &status_mutex );
}


void stop_doingg( void )
{
        pthread_mutex_lock( &status_mutex );
        status = 0;
        pthread_mutex_unlock( &status_mutex );
}

int is_good_to_go( void )
{
        int temp;

        pthread_mutex_lock( &status_mutex );
        temp = status;
        pthread_mutex_unlock( &status_mutex );

        return temp;
}

then:

void *run_thread(void *ptr)
{
    if (is_monitor_thread)
    {
        while (check_system_status() < 0)
        {
            sleep (1);
        }
        good_to_go();
    }
    else
    {
//below while loop looks ugly. 
//is there a way to get notified once "status" is changed to 1?
        while( !is_light_turned_on() )
        {
            sleep (1);   
        }
}

Upvotes: 2

Views: 80

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118310

You are looking for condition variables.

See the following man pages:

pthread_cond_init()
pthread_cond_signal()
pthread_cond_broadcast()

Upvotes: 4

Related Questions