Chris Coleman wrote:
Hi,
I know at present that the Boost Threads implementation does not provide a terminate() / cancel() function, but the documentation suggests that work is in progress to implement this feature once a safe and portable way is found. I was just wondering whether this will appear soon in future releases, or if it is likely to be some time?
I don't think you're likely to see it any time soon.
At present I can kill a thread internally by simply throwing an exception and not catching it.
That might work on whatever platform you're currently using, but I would expect it to abort the program, just as in a single-threaded program. That's what happens under Windows.
But externally I cannot.
I have a thread pool server I built some time ago using the pthread API and I'm porting it to use Boost Threads. The server has add() and remove() thread methods. Within the remove function under the pthread implementation I could call pthread_cancel(thrID) and that would be that,
The interaction of pthreads with C++ is regrettably undefined. Some implementers have integrated cancellation with exception-handling, but that raises difficult issues such as what happens when a cancellation exception is caught and not re-thrown, and whether C library functions can be cancellation points in a C++ program given that the C++ standard says they won't throw. (Of course multithreaded programs are outside the scope of the current standard, but one might hope that the Principle of Least Surprise would be applied to multithreading extensions.)
Obviously I cant call thread.cancel() as I'd like here and was wondering if there were any simple ways to signify that a particular thread should terminate?
Asynchronous cancellation of C++ code is almost invariably unsafe. Synchronous cancellation may be simulated by setting a simple flag polled by the cancellable thread. (Appropriate memory barriers must be placed after setting and before polling the flag. In the absence of portable memory barrier facilities, one may protect the flag with a mutex, though that's annoyingly heavyweight.) However this does not help if the thread is sleeping. Depending on why and how the thread is sleeping, it may be possible to interrupt such a sleep by sending the thread a signal or writing to a pipe. Ben.