jeudi 26 mai 2016

How to submit thread pool with templatised member function (need to modify the members inside function)

I am trying to re-use a simple thread pool mentioned in SO -

class thread_pool 
{
      thread_safe_queue<std::function<void()> work_queue; // need to submit  fun(v) of class A where v is vector<string> here.

  void worker_thread() {
       while(!done)
       {         
           std::function<void()> task;
           if(work_queue.try_pop(task)) 
           {
               task();  // how should my function MyClass::Func(a,b) be called here?                    
           }
          else 
          {
              std::this_thread::yield();
          }
      }
  }
  // -- Submit a task to the thread pool
  template <typename FunctionType>
  void submit(FunctionType f) {
  work_queue.push(std::function<void()>(f)); //how do i submit something like A.fun(v) ?
 }

}

Now i need to submit a task which is a member function of a templatized class in the queue

template<class T>
class A
{
private:
int x ;
public:
    void fun(std::vector<std::string> & items) 
    {
        //do somehting with items.
         x = 5; // modify the members.
    }// please note that i need to modify members in this function in submitted thread.
};

so finally i need something like-

thread_pool tp;
// a member function of class obj A (a) submitted with vector<string> v.
tp.submit(&A<int>::fun, std::ref(a), v);

the queries i have is how will the task queue signature look like to execute above mentioned task? How would I need to change the thread_pool class in order to run this templatized member function?How can I call the submit Function in my code?

I saw a similar question here but still wondering about it. An example of the same would really be helpful.

Thank you very much for your help.

Aucun commentaire:

Enregistrer un commentaire