Boost logo

Boost Users :

Subject: Re: [Boost-users] problems with boost bind and boost thread
From: Anthony Williams (anthony.ajw_at_[hidden])
Date: 2012-03-22 11:32:11


On 22/03/12 15:16, Igor R wrote:
>> I want co call a function or method in a separate thread periodically.
>> Therefore my CCycleThread class starts the execute method as thread and
>> calls the user function object in a loop. The user can pause, resume and
>> finish the thread if he wishes.
>> To separate the worker code from the threading code I build this wrapper
>> around boost thread with pause and resume methods.
>
> <...>
> Yes, I understand why such a design can be uselful. What I said is
> that I didn't realise how to separate binder/not-a-binder cases.
> But after thinking a bit... actually, you can just define 2 function
> templates in a straight-forward way:
>
> // simple functor/function case
> template<typename T>
> CCycleThread(T t)
> {
> m_thread.reset(new
> boost::thread(boost::bind(&CCycleThread::execute<T>, this, t)));
> }
>
> // binder case
> template<class R, class F, class L>
> CCycleThread(boost::_bi::bind_t<R,F,L> t)
> {
> m_thread.reset(new
> boost::thread(boost::bind(&CCycleThread::execute<boost::_bi::protected_bind_t<boost::_bi::bind_t<R,F,L>
>>> , this, boost::protect(t))));
> }

Even simpler: just wrap the supplied function/binder in boost::function.

CCycleThread(boost::function<void()> t)
{
    m_thread.reset(new
boost::thread(boost::bind(&CCycleThread::execute, this, t)));
}

That way you don't even need to template execute: just have it accept a
boost::function<void()>

Anthony

-- 
Author of C++ Concurrency in Action     http://www.stdthread.co.uk/book/
just::thread C++11 thread library             http://www.stdthread.co.uk
Just Software Solutions Ltd       http://www.justsoftwaresolutions.co.uk
15 Carrallack Mews, St Just, Cornwall, TR19 7UL, UK. Company No. 5478976

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