0

I would like to push elements into a queue using vector of threads, but am getting an error: no matching constructor for initialization of thread. Can you please help me to fix it.

#include <thread>
#include <queue>
using namespace std;
void thread_spawn_q(queue<int> &q)
{
    vector<thread> ths;
    for (int i = 1; i <= 1000; i++)
    {
        ths.push_back(thread(&queue<int>::push, &q, i));
    }
    for (auto &th : ths)
    {
        th.join();
    }
}
int main()
{
    queue<int> q = queue<int>();
    thread_spawn_q(q);
    return 0;
}
  • As in duplicate question you need: `ths.push_back(std::thread(static_cast::*)(int&&)>(&std::queue::push), &q, i));` – a bit more elegant is `ths.emplace_back(static_cast::*)(int&&)>(&std::queue::push), &q, i);`... – Aconcagua Feb 03 '22 at 14:39
  • The error is that `&queue::push` is ambiguous as its an overloaded method, you need `ths.push_back(thread(static_cast::*)(const int&)>(&queue::push), &q, i));` or just use a lambda instead `ths.push_back(thread([&q, i]{q.push(i);}));` – Alan Birtles Feb 03 '22 at 14:39
  • It is working now. Thank you Aconcagua and Alan Birtles. – Suresh Atukuri Feb 03 '22 at 16:20

0 Answers0