Boost logo

Boost Users :

Subject: Re: [Boost-users] how to reuse a thread
From: Vicente J. Botet Escriba (vicente.botet_at_[hidden])
Date: 2013-03-17 14:17:35


Le 17/03/13 19:10, Vicente J. Botet Escriba a écrit :
> Le 17/03/13 18:05, Victor Yankee a écrit :
>> Hello,
>>
>> I would like to create a boost thread that can be reused to run a
>> variety of functions each with different number of args of different
>> types. I am using C++11 gnu compiler and so maybe a solution using
>> variadics might work?
>>
>> I posted to here:
>> http://stackoverflow.com/questions/15237426/can-a-thread-be-reused-to-run-variadic-functions
>>
>> But I am not understanding how.
>>
> The proposed solution allow you to pass a Callable without arguments
> and don't returning anything (void(void)). Using lambdas or std::bind
> you are able to call any function with a variable number of arguments.
>
> | loop.postTask([]{foo("task", 0);});
>
> or
>
> || loop.postTask(std::bind(foo,"task", 0));
> |
> What you don't understand? Are you looking for
> | loop.postTask(foo,"task", 0);
> |
> ?
>
> In this case you need to forward these arguments to bind
>
> template <typename F, typename ...Args>
> | void postTask(F&& f, Args&&... args)
> {
> std::lock_guard<std::mutex> lock(m_Mutex);
> m_Tasks.push(std::bind(std::forward<F>(f),|||std::forward<Args>(|args)...));
> }|
>
> or something like that.
BTW, even if you don't need to store the pending work on a queue, you
need to store the next function and here std::function<void(void)> could
be used also.

| bool postTask(F&& f, Args&&... args)
     {
         std::lock_guard<std::mutex> lock(m_Mutex);
         if (busy) return false;
          m_Task =std::bind(std::forward<F>(f),|||std::forward<Args>(|args)...);
||| return true;|
     }|

Vicente



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