Question: I have a C++ program on Linux (CentOS 5.3) spawning multiple threads which are in an infinite loop to perform a job and sleep for certain minutes.
Now I have to cancel the running threads in case a new configuration notification comes in and freshly start new set of threads, for which i have used pthread\_cancel.
What I observed was, the threads were not getting stopped even after receiving cancel indication,even some sleeping threads were coming up after the sleep was completed.

As the behavior was not desired, usage of pthread\_cancel in the mentioned scenario raises question about being good or bad practice. 

Please comment on the pthread\_cancel usage in above mentioned scenario.

Answer: 
If you are writing exception safe C++ code (see <http://www.boost.org/community/exception_safety.html>) than your code is naturally ready for thread cancellation. [glibs throws C++ exception on thread cancel](http://udrepper.livejournal.com/21541.html), so that your destructors can do the appropriate clean-up.
I'd use boost::asio.

Something like:

```
struct Wait {
  Wait() : timer_(io_service_), run_(true) {}

  boost::asio::io_service io_service_;
  mutable boost::asio::deadline_timer timer_;
  bool run_;
};

void Wait::doWwork() {
  while (run) {
    boost::system::error_code ec;
    timer_.wait(ec);
    io_service_.run();
    if (ec) {
      if (ec == boost::asio::error::operation_aborted) {
        // cleanup
      } else {
        // Something else, possibly nasty, happened
      }
    }
  }
}

void Wait::halt() {
  run_ = false;
  timer_.cancel();
}

```

Once you've got your head round it, asio is a wonderful tool.