首页 > 解决方案 > std::thread 编译问题

问题描述

这个 main 函数的目标是找到一个范围内的素数数量,使用线程将问题划分为选定数量的线程。std::thread由于这些论点,我遇到了问题并出现错误。我不确定如何解决它。任何帮助将不胜感激。

这是错误:

error: no matching function for call to 'std::thread::thread(void (&)(int, int, int*, int), int&, int&, int [numThreads], int&)' std::thread* th = new std::thread(myRun, minThread, maxThread, threadCount, i);
#include <iostream>
#include <thread>

static int isPrime(int n);
static int primesInRange(int min, int max);
void myRun(int min, int max, int* threads, int index);

int main()
{
    std::thread* ths[2];
    int threadCount[2];

    for (int i = 0; i < 2; i++)
    {
        std::thread* th = new std::thread(myRun, min, max, threadCount, i);
        ths[i] = th;
    }

    for (int i = 0; i < 2; i++)
    {
        ths[i]->join();
    }

    int result = 0;
    for (int i = 0; i < 2; i++)
    {
        result = result + threadCount[i];
    }

    std::cout <<"text here\n";
}


void myRun(int min, int max, int* threads, int index)
{
    threads[index] = primesInRange(min, max);
}

标签: c++multithreadingpthreadsstdstdthread

解决方案


min and max are undefined variable names when you invoke this line:

 std::thread* th = new std::thread(myRun, min, max, threadCount, i);

For what it's worth, never a good idea to name a variable min or max. Often gets confused with std::min, std::max and a lot of code bases have similarly named macros.


推荐阅读