Search code examples
handlersleepwaitthread-sleep

Make Thread sleep first before it runs


How can I make my thread sleep first before it runs? I know how to get sleep to work, however, whenever my program is run, the thread immediately runs. I want it to WAIT once it is first created to start running. (I am using handlers)


Solution

  • You cannot control when threads are scheduled. If you want it to go to sleep, have the first statement in the thread subroutine do a wait on a condition or something like that and when you are ready you can broadcast to that condition. In pseudo-code:

    get-lock
    if (we-are-still-supposed-to-sleep)
      pthread_cond_wait()
    release-lock
    

    I suppose you could have the parent hold the lock while creating the children and then all they have to do is:

    get-lock
    release-lock
    

    and avoid the condition thing.