【问题标题】:Problem with thread function arguments in C++C++中线程函数参数的问题
【发布时间】:2021-08-03 10:16:58
【问题描述】:

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

这是错误:

错误:没有匹配函数调用 '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()
{
    int min = 0;
    int max = 3;
    int numThreads = 1;

    std::thread* ths[numThreads];
    int threadCount[numThreads];

    int minThread = 0;
    int maxThread = 0;
    int formerMax = 0;

    for (int i = 0; i < numThreads; i++)
{
    if (i == 0)
    {
        minThread = min;
        maxThread = min + (max - min)/numThreads;
        formerMax = maxThread;
    }
    else
    {
        minThread = formerMax + 1;
        maxThread = minThread + (max - min)/numThreads;
        formerMax = maxThread;
    }

    if (maxThread > max)
    {
        maxThread = max;
    }

    std::thread* th = new std::thread(myRun, minThread, maxThread, threadCount, i);
    ths[i] = th;
}
}


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

【问题讨论】:

  • 有时您必须使用 明确指定模板化函数。我也想知道如果你转换 args 编译器是否会选择它......
  • 这对我和compiles in gcc 来说都不错 - 您使用的是哪个编译器(包括版本)?
  • 不可重现 ideone.com/FdNCcH 请编辑您的问题以包含 minimal reproducible example
  • @KenY-N MinGW gcc 8.1.0
  • @Slava 我已经更新了我的帖子,对此感到抱歉。

标签: c++ multithreading stdthread


【解决方案1】:

如果您遵循错误消息,编译器会进一步告诉您问题所在:

prog.cpp:41:82: 注意:可变大小数组类型‘int (&)[numThreads]' 不是有效的模板参数 std::thread* th = new std::thread(myRun, minThread, maxThread, threadCount, i);

注意 C++ 中不允许使用 VLA,请改用 std::vector,您仍然可以通过指向 int 的指针传递它的数据

std::vector<std::thread> ths( numThreads );
std::vector<int> threadCount( numThreads );

....
ths[i] = std::thread(myRun, minThread, maxThread, threadCount.data(), i);

但传递对int 的引用会更简洁:

void myRun(int min, int max, int &count );

然后:

ths[i] = std::thread(myRun, minThread, maxThread, std::ref( threadCount[i] ) );

【讨论】:

    【解决方案2】:
    int numThreads = 1;
    
    std::thread* ths[numThreads];
    int threadCount[numThreads];
    

    这不是合法的 C++ 代码。 C++ 没有变长数组。一些编译器将它们作为扩展提供,但如果你使用它们,你基本上是靠你自己的。他们与其他语言的交互没有很好的记录。在这里,您的模板参数推导无法按预期工作。

    不要在 C++ 中使用变长数组,而是使用 std::vector

    在不相关的注释中,您不需要new 线程对象或使用指向std::thread 的指针。试试std::vector&lt;std::thread&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      • 2012-10-24
      相关资源
      最近更新 更多