1
void main()
{
    .....
    pthread_mutex_init(&lock)
    pthread_create(fun,...)
    pthread_create(fun,...)
    pthread_create(fun,...)
}

void fun()
{
    pthread_mutex_lock(&lock)
    ...........
    pthread_mutex_unlock(&lock)
}

In the code above, I created 3 threads calling same function fun. I can tell you that execution of fun takes long than creating the threads. So there are 3 threads initially. But 1st thread is already executing after taking lock. Now 2nd and third thread are waiting. My question is once the lock is released which thread will be scheduled. Is it 2nd thread and then third or depends on the scheduler. Does scheduler maintain any kind of queue for the waiting threads and schedules it in FIFO manner?

Harsha
  • 323
  • 1
  • 17

1 Answers1

0

No, it does not work like a FIFO. One thread at random will be woken up.

redneb
  • 21,794
  • 6
  • 42
  • 54
  • Thanks. Is there a work-around for scheduling 2nd thread immediately after 1st thread exits? – Harsha Sep 04 '16 at 12:11
  • You have to implement a fair mutex yourself. It can be done by using standard mutexes. See also: http://stackoverflow.com/questions/5385777/implementing-a-fifo-mutex-in-pthreads – redneb Sep 04 '16 at 12:13