我的线程程序存在问题。我知道问题是什么,我只是不知道如何解决它。我正在设置一个任意数量的线程来创建一个mandelbrot集,然后将其写入ppm文件。我正在使用std :: thread的向量并调用Mandelbrot类成员函数来执行线程。问题出在这里。我正在调用编译器不喜欢的void(void)函数。我如何解决这个问题,以便线程执行void(void)函数?我的代码如下:
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;
}
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);
}
}
答案 0 :(得分:5)
threads.emplace_back(mandelbrot.mandelbrotsetThreaded());
// ^^
// note this!
该小行实际上会调用 mandelbrot.mandelbrotsetThreaded()
并尝试使用返回值传递给threads.emplace_back()
。当返回类型指定为void
时,它会发现这很困难: - )
你想要的是函数(地址)本身,而不是函数的结果,如:
threads.emplace_back(mandelbrot.mandelbrotsetThreaded);