Click to See Complete Forum and Search --> : Stop and Start pthreads


andre.heller
June 21st, 2011, 09:00 AM
I have got pthreads in m C code. I am doing a project on VoIP and I need to start the pthreads and make them work with some milliseconds sleep time. Right now my threads are running and when I get a session end from the server I need to stop the running threads and restart them again new from the beginning.

My code looks something like this:

send_recv_data()
{

pthread_create(thread2, NULL, send_thread, NULL);
pthread_create(thread3, NULL, recv_thread, NULL);
}

void *first_thread(void *arg)
{
/*if some condition met the start the routine for creation of two threads one for receiving and one for sending data*/
if(cond == TRUE){
send_recv_data();
}

}
main()
{
pthread_create(thread1, NULL, first_thread, NULL);
}

My question is that once i receive a message from the other user agent that it is sending me no more data then I need to stop both the send and recv threads and then finally first_thread which is responsible for the creation of the other two threads. Once i stop all the threads I need to restart them again. I tried using mutexes and conditional variables but all went in vain.

Any idea of how I can overcome this, may be a small piece of simple code would be much more helpful

Thanks

D_Drmmr
June 22nd, 2011, 06:42 AM
Why do you need to stop the threads and then start them again?
It's usually a better design to have your threads run a loop to process tasks that are assigned to it. Tasks are typically some kind of function object and each thread typically has a queue of tasks that need to be processed (or you can share a queue between several threads). When there is nothing to be processed (i.e. queue is emtpy) the thread just waits until something is pushed onto the queue.