Howard Shane
Howard Shane

Reputation: 956

how does it work? pthread_cond_signal() and pthread_cond_wait()

I have below code to synch multiple threads. In below code, with creating 16 threads, looks like only 1 wait successfully; 4 is keeping wairing; 11 does not need to wait (as flag has been set to 1).

Could you please take a look and see where is the problem? thanks!

static int can_go = 0;
static pthread_mutex_t go_mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t wait_cond = PTHREAD_COND_INITIALIZER;

void set_go( void )
{
    pthread_mutex_lock( &go_mtx );
    can_go = 1;
    pthread_cond_signal(&wait_cond);
    pthread_mutex_unlock( &go_mtx );
}

int wait_go( void )
{
    pthread_mutex_lock( &go_mtx );
    while(can_go == 0)
    {
        printf("beging waiting ... \n");
        pthread_cond_wait(&wait_cond, &go_mtx); 
        printf("waiting done\n");
    }
    printf("outside of while waiting !!!\n");
    pthread_mutex_unlock( &go_mtx );
}

Then my main() created 16 threads, and in each thread, I did:

void *run_thread(viod *ptr)
{
    ..............
    if (is_sync_thread){  //if this is a special sync thread, do something and trigger other threads
            .............
            set_go();
    }
    else{   //this is worker, wait for sync thread finish and set_go()
        wait_go()
        ....................
    }   
}

This is the output:

beging waiting ... 
beging waiting ... 
beging waiting ... 
beging waiting ... 
beging waiting ... 
 wait done
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!
outside of while waiting !!!

Upvotes: 0

Views: 340

Answers (1)

David Schwartz
David Schwartz

Reputation: 182743

You called pthread_cond_signal, which is only guaranteed to wake one thread. You want pthread_cond_broadcast, which is guaranteed to wake all waiting threads.

Upvotes: 4

Related Questions