C STD ::线程无效的void表达式使用

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

本文关键字:表达式 void 无效 STD 线程      更新时间:2023-10-16

我的线程程序有问题。我知道问题是什么,我只是不知道如何解决。我正在设置任意数量的线程来创建一个mandelbrot集,然后将其写入PPM文件。我正在使用std :: thread的向量,并调用mandelbrot类成员函数进行线程。问题发生在这里。我正在调用编译器不喜欢的void(void)函数。如何修复此问题,以使线程执行void(void)函数?我的代码如下:

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);
   }
}
threads.emplace_back(mandelbrot.mandelbrotsetThreaded());
//                                                   ^^
//                                               note this!

那小线实际上将 call mandelbrot.mandelbrotsetThreaded(),并尝试使用返回值传递给threads.emplace_back()。当将返回类型指定为void: - )

时,它会发现这很困难

您想要的是函数(地址)本身,而不是功能的结果,例如:

threads.emplace_back(mandelbrot.mandelbrotsetThreaded);