Search code examples
cmultithreadingpthreadsmutexthread-synchronization

Thread synchronization in Linux?


I am writing a code wherein I am making my threads wait till I do a pthread_cond_broadcast. I have three threads in this code. Threads line2_thread and line3_thread, are running in the order of their priority like they are supposed to run. However, my third thread doesn't even enter its thread function (line4_thread). Can anyone tell me why is my main() not being able to call my line4_thread ? pthread_cond_t sstart; pthread_mutex_t sstart_mutex;

void *l3_thread(void *arg){

pthread_mutex_lock(&sstart_mutex);
pthread_cond_wait(&sstart, &sstart_mutex);
pthread_mutex_unlock(&sstart_mutex);
/*do something*/

pthread_exit(NULL);

}

void *l2_thread(void *arg){

pthread_mutex_lock(&sstart_mutex);
pthread_cond_wait(&sstart, &sstart_mutex);
pthread_mutex_unlock(&sstart_mutex);
/*do something*/

pthread_exit(NULL);

}


void *l4_thread(void *arg){

pthread_mutex_lock(&sstart_mutex);
pthread_cond_wait(&sstart, &sstart_mutex);
pthread_mutex_unlock(&sstart_mutex);
/*do something*/

pthread_exit(NULL);

}

int main(){

pthread_cond_init(&sstart, NULL);

//thread creation

pthread_cond_broadcast(&sstart);
pthread_cond_destroy(&sstart);
    pthread_mutex_destroy(&sstart_mutex);

return 0;
}

Solution

  • I think you have a few problems here. With apologies (I'm on my phone so typing a long answer is hard) I'm just going to focus on a couple things, since it's not 100% clear to me what you're actually trying to do.

    When all your threads start they all try to acquire the mutex, and only one succeeds. Probably l3 but I don't think that's guaranteed here. It then calls the pthread_cond_wait and unlocks the mutex allowing one of the other threads to reach its pthread_cond_wait. But in the meantime. You've allowed your main thread to call pthread_cond_broadcast, and you've taken no steps to synchronize this with the other threads. It may happen before the others get unblocked from waiting for the mutex, and before their wait call, so they could miss the signal and block forever.

    Further, I think it's a bit sketchy to immediately call pthread_cond_destroy. Like I said there's no synchronization between your main thread and your worker threads, so it's possible you could call pthread_cond_broadcast followed by pthread_cond_destroy, so some of your threads might be calling pthread_cond_wait on an invalid condition variable and deadlock.

    Check the return values of pthread_cond_wait. If I'm right, it might return EINVAL in some cases. But I haven't tested this so there might be a flaw in my reasoning.