0

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);
   }
}
Josh Davis
  • 157
  • 3
  • 10
  • 3
    @paxdiablo Gave you the right answer, so here is some advice: Don't use a mutex to guard `cur_row`, instead, make it an `std::atomic<>`. – JustSid Jan 25 '14 at 04:52
  • Thanks for the advice. I've never done anything with threads before. It's all new to me. – Josh Davis Jan 25 '14 at 05:07

1 Answers1

5
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);
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • To appropriately use this class function would the following be correct: threads.emplace_back(&Mandelbrot::mandelbrotsetThreaded, mandelbrot); – Josh Davis Jan 25 '14 at 05:17