I'm making a version of the producer-consumer problem in C++20.
I need to work on a number of buffers, each having their own threads of producers and consumers, the number of threads being an argument. Seeing as the number of threads isn't a constant, I decided to store the threads in a vector, while the vectors of producers (consumers) for each buffer are stored in another vector.
I've created a minimal reproducible example of the code that's giving me an error:
#include <iostream>
#include <thread>
#include <semaphore>
#include <mutex>
#include <vector>
struct Buffer {
std::counting_semaphore<1> full{0};
std::counting_semaphore<1> empty{1};
};
void producer(Buffer buffer) {
while(true)
{
buffer.empty.acquire();
buffer.full.release();
}
}
int main() {
std::vector<std::vector<std::thread>> producers;
for(int i = 0; i< 2; i++)
{
std::vector<std::thread> p;
producers.push_back(p);
}
std::vector<Buffer> buffers;
for(int i = 0; i<2; i++)
{
Buffer buffer;
buffers.push_back(buffer);
}
int counter = 0;
for(auto &vec: producers)
{
std::thread thread(producer, buffers[counter]); // error here
vec.push_back(std::move(thread));
counter++;
}
}
The error on the indicated line is
error: static assertion failed: std::thread arguments must be invocable after conversion to rvalues.
What could be causing this problem?