C++0x interruptible thread

Hi,
it is possible interrupt a C++0x thread?
What do you mean? From outside the thread?
Yes, from another thread! (from the parent thread)
This is almost never a good idea. Why do you need to do this?
The "childs" thread have an infinite loop. When my process terminate, I should report it to all the threads so that they could finish.
Use condition variables to signal the threads to break out of the loop, clean up, and terminate on their own, then have the main thread wait for each of them.

Killing a thread is the first thing that comes to mind when one is first starting with threading, but you should really only do it when there's no other choice.
Besides condition variables, you can a synchronized message queue that is shared among all the threads. When request come into parent thread, parent thread put the request on the queue and the child thread will pick them up. Likewise in order to terminate, parent thread put TERMINATE requests on the message queue and let the child threads pick them up and terminate one by one on their own. Parent thread need to keep track on the number of child threads it spawns so all child receive the TERMINATE requests. The number is also for parent thread to know the total number of child threads that terminated normally else may need a force-kill of that child (this is last resort).

There are other ways but the general idea should be the same. Parent thread need to 'signal' or find a way to communicate with their child it is time to TERMINATE. The communication mechanism can be condition variables, synchronized message queue and etc etc.
Ok, but I have this problem:

My child thread actually have an infinite loop that wait on socket TCP/IP.

The loop is like this:

1
2
3
4
5
while (1)
{
 string msg = revcMessageFromSocket();
 //...
}


If I use a queue message for pass the TERMINATE request to my child, the loop becomes:

1
2
3
while (recvMessageFromSocket() || wait_and_pop()) //wait_and_pop() wait  a message in queue
{
}


But two function recvMessageFromSocket() and wait_and_pop() are bloking and this code don't work.

If I use another version of my loop, with nonblocking functions:

1
2
3
while (recvMessageNoBlocking() || tryPop())
{
}


This code consumes many CPU cycles because it alway comes back to check the while contition.

Wath is the correct solution?





Use a function like Windows Sleep() to slow down how many cycles per second the loop does.
Alternatively, do you have a blocking recv() with a timeout?
Topic archived. No new replies allowed.