Boost logo

Boost Users :

From: Søren Dreijer (halloko_at_[hidden])
Date: 2006-12-27 15:49:11


Ah, excellent! I seem to recall a post somewhere mentioning that relying on volatile might not always work on multiprocessor systems. Is that something to worry about?Quick follow-up question:
Why do you use auto_ptr<bool> when passing the flag_guard to the thread when you release it right afterwards? Is there a chance that thread's constructor or bind() might throw an exception?Thanks for the quick response,
Soren

> Date: Wed, 27 Dec 2006 20:45:40 +0100> From: sebastian.redl_at_[hidden]> To: boost-users_at_[hidden]> Subject: Re: [Boost-users] [Boost.Threads] Exiting Thread Properly> > 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 mailing list> Boost-users_at_[hidden]> http://lists.boost.org/mailman/listinfo.cgi/boost-users
_________________________________________________________________
Call friends with PC-to-PC calling -- FREE
http://get.live.com/messenger/overview



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