2

I have a thread pool with submit:

template<typename F, typename... Args>
void submit(F f, Args... args) {
    auto work = [f,args...]() { f(args...); };
    work_queue.push_back( work );
}

And I need to pass function from a non-copyable class or an object of this class as an argument. What I have already tried is to pass a unique pointer, it works if I directly put it in function, but not when I do it via submit

std::unique_ptr<Dispatcher> valuePtr(new Dispatcher(5));
index_file(buffer, conf, std::ref(res), std::ref(mutex), std::move(valuePtr)); \\ work
t.submit(index_file, buffer, conf, std::ref(res), std::ref(mutex), std::move(valuePtr)); \\ don't work, because submit calls to deleted constructor of valuePtr
void index_file(const std::string &filename, const configuration_t &conf, std::atomic<int> &res, std::mutex &m,
                std::unique_ptr<Dispatcher> d) {
    // some code
    d->addMap(map);
}

I can't do function addMap static as it adds elements to the queue in Dispatcher. Also, I can't make Dispatcher copyable, because it uses mutex.

BZKN
  • 1,499
  • 2
  • 10
  • 25
Diana Deer
  • 35
  • 4
  • Does this answer your question? [How to pass a reference through a parameter pack?](https://stackoverflow.com/questions/9103076/how-to-pass-a-reference-through-a-parameter-pack) – Yksisarvinen Apr 22 '21 at 10:21
  • That question is about lvalue reference, but perfect forwarding handles all types of references. – Yksisarvinen Apr 22 '21 at 10:22
  • 1
    Or maybe this question would be more fitting, if you need to capture pack in lambda: [c++ lambdas how to capture variadic parameter pack from the upper scope](https://stackoverflow.com/questions/47496358/c-lambdas-how-to-capture-variadic-parameter-pack-from-the-upper-scope) – Yksisarvinen Apr 22 '21 at 10:26
  • 1
    Your lambda inside `submit` captures `args` by value (copying them). You need to move them into the lambda. Also, if you make `Dispatcher` movable, you can get rid of the `unique_ptr`. – super Apr 22 '21 at 10:30
  • It was easier than I thought. I just give a reference, not a pointer. It didn't work before - I don't know why, maybe I had some other problems, so I started to change all into pointers and came to this awful code ) Thanks for answers – Diana Deer Apr 22 '21 at 11:17
  • 1
    If you pass `unique_ptr` by reference, how do you ensure it lives until the task is completed later (in another thread)? – rustyx Apr 22 '21 at 11:22
  • But before this I managed to move them in submit ) Sadly, It was unnecessary work – Diana Deer Apr 22 '21 at 11:25

0 Answers0