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??

pthread_cond_timedwait() is a usual solution.

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;


}

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?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.