I am using
a) Linux
b) Pthreads

I want to write a program, with two pthreads, to cater for two queues of people. People arrive at each queue at a random interval of 1 - 10 seconds.

Each time a person arrives, print out the number of people in each queue to the screen.

Apparently sleep() pauses the whole program, how can a pause one particular thread??

I have looked at sample code, and cannot seem to implement that, for example it needs a condition. I want something like sleep, that can be used in the thread with no conditions.

Some kind of skeleton example of what I'm trying to do (I can create and join pthreads fine, just have limited knowledge when it comes to mutexes and conditions)

bool run;

int getRandom()
{
    return random number between 1 and 10
}

void thread1()
{
   while(run)
   {
      temp = getRandom();
      pause thread for temp seconds;
   }
}

void thread2()
{
   while(run)
   {
      temp = getRandom();
      pause thread for temp seconds;
   }
}

int main()
{
   create thread to run a timer, after 10 mins, set run to false

   create thread 1;
   create thread 2;
   join thread1;
   join thread2;


}

Edited 5 Years Ago by John Linux: incomplete

In your particular situation the condition is never going to be signalled. Just declare one in the pause() function, something along the lines of

void pause_thread(struct timespec * wakeuptime)
{
    pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
    pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER;

    pthread_mutex_lock(&mx);
    while(pthread_cond_timedwait(&cond, &mx, wakeuptime) != ETIMEDOUT)
        ;
    pthread_mutex_unlock(&mx);
    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&mx);
}

This is a demo. Of course you may want to have cond and mx to be created once and destroyed once.
> just have limited knowledge when it comes to mutexes and conditions

That's OK. You want to learn, don't you?

Edited 5 Years Ago by nezachem: n/a

This article has been dead for over six months. Start a new discussion instead.