Boost logo

Boost Users :

From: Sebastian Redl (sebastian.redl_at_[hidden])
Date: 2006-12-27 14:45:40


Soren Dreijer wrote:
> I'm wondering what the best approach is to signal a
> thread to exit.
Just allocate a boolean variable for each thread and pass the address to
the thread starting function. The loop of the thread breaks if the flag
is reset; the thread exits. This scheme is so simple that it doesn't
even require synchronization beyond making the pointer the thread
accesses volatile.
You could use a shared_ptr to manage the memory, but personally I would
simply use a scoped_ptr in the thread's main function.
The following code is conceptual. I can't remember the exact API of
Boost.Threads.

void thread_proc(volatile bool *flag)
{
  scoped_ptr<bool> guard(flag);
  while(*flag) {
    // Work
  }
}

map<threadid, bool *> flags;

void create_worker()
{
  auto_ptr<bool> flag_guard(new bool(true));
  thread t(bind(&thread_proc, flag_guard.get()));
  // Thread is started. This ensures that it will release the memory.
  bool *b = flag_guard.release();

  flags.insert(make_pair(t.get_id(), b));
}

// Note: this function needs to synchronize if you can't ensure that it
will only be ever called once
// for any given thread id.
void signal_worker(threadid id)
{
  flag_iterator i = flags.find(id);
  if(i != flags.end()) {
    bool *b = i->second;
    flags.remove(id);
    *b = false;
  }
}

You will need to synchronize map access, of course.

Sebastian Redl


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net