Josh Davis
Josh Davis

Reputation: 157

C++ std::thread invalid use of void expression

I'm having an issue with my threading program. I know what the issue is, I just don't know how to fix it. I'm setting up an arbitrary number of threads to create a mandelbrot set and then to write it out to a ppm file. I'm using a vector of std::thread's and calling a Mandelbrot class member function to do the threading. The issue occurs here. I'm calling a void(void) function in which the compiler does not like. How do I go about fixing this so that the thread will execute the void(void) function? My code is below:

main.cpp

int main(int argc, char **argv) {
   const unsigned int WIDTH = 1366;
   const unsigned int HEIGHT = 768;
   int numThreads = 2;

   Mandelbrot mandelbrot(WIDTH, HEIGHT);

   if(argc > 1) {
      numThreads = atoi(argv[1]);
   }

   std::vector<std::thread> threads;

   for(int i = 0; i < numThreads; ++i) {
      threads.emplace_back(mandelbrot.mandelbrotsetThreaded());
   }

   for(int i = 0; i < numThreads; ++i) {
      threads[i].join();
   }

   return 0;
}

mandelbrot.cpp

void Mandelbrot::mandelbrotsetThreaded() {
   while(true) {
      int row = 0;
      {
         std::lock_guard<std::mutex> lock(row_mutex);
         row = cur_row++;
      }
      if(row == width) return;
      createMandelbrotSet(row);
   }
}

Upvotes: 0

Views: 3627

Answers (1)

paxdiablo
paxdiablo

Reputation: 881403

threads.emplace_back(mandelbrot.mandelbrotsetThreaded());
//                                                   ^^
//                                               note this!

That little line will actually call mandelbrot.mandelbrotsetThreaded() and attempt to use the return value to pass to threads.emplace_back(). It will find this rather difficult when the return type is specified as void :-)

What you want is the function (address) itself, rather than the result of the function, something like:

threads.emplace_back(mandelbrot.mandelbrotsetThreaded);

Upvotes: 5

Related Questions