正确的线程调用语法?错误:没有匹配对 std::thread::thread(<大括号括起来的初始值设定项列表>)

Proper thread call syntax? error: no matching call to std::thread::thread(<brace-enclosed initializer list>)

本文关键字:thread 起来 列表 gt 错误 语法 调用 线程 std lt      更新时间:2023-10-16

>我正在尝试创建一个运行类函数的线程。我认为我做错了什么的地方靠近底部,我有RowChecker r0(puz, 0, s); thread rt0 {r0.check()};。我的编译器(g++)告诉我有no matching function for call to ‘std::thread::thread(<brace-enclosed initializer list>)’所以我明白我没有正确拨打电话。格式化此调用以创建新线程的正确方法是什么?

#include <iostream>
#include <thread>
using namespace std;
class Sum
{
private:
    int sum;
public:
    Sum();
    int getSum();
    void addSum();
};
class RowChecker
{
private:
    int puz[9][9];
    int myRow;
    Sum* sum;
public:
    RowChecker(int puzzel[9][9], int row, Sum* shared);
    void check();
};
Sum::Sum() {
    sum = 0;
}
int Sum::getSum() {
    return sum;
}
void Sum::addSum() {
    ++sum;
}
RowChecker::RowChecker(int puzzel[9][9], int row, Sum* shared) {
    for (int i=0; i<9; ++i) {
        for (int j=0; j<9; ++j) {
            puz[i][j] = puzzel[i][j];
        }
    }
    myRow = row;
    sum = shared;
}
void RowChecker::check() {
    char table[] = {0,0,0, 0,0,0, 0,0,0};
    for (int i=0; i<9; ++i) {
        if (puz[i][myRow]<10 && puz[i][myRow]>=0) {
            table[puz[i][myRow]] = 1;
        }
    }
    for (int i=0; i<9; ++i) {
        if (table[i]==0) {
            return;
        }
    }
    sum->addSum();
}
void readPuzzel(int puz[9][9]){
    for (int i=0; i<9; ++i) {
        for (int j=0; j<9; ++j) {
            puz[i][j] = rand() % 10;
        }
    }
}
int main()
{
    Sum s;
    int puz[9][9];
    readPuzzel(puz);
    RowChecker r0(puz, 0, &s);
    thread rt0 {r0.check()};
    rt0.join();
    cout << "Sum s is " << s.getSum() << endl;
    return 0;
}

对不起,长度。另外,我知道传递数组是邀请错误加入的好方法。我打算把东西切换到矢量。

你需要将一个函数传递给 thread 的构造函数。在您的代码中,您正在调用r.check()并将结果传递给 thread 的构造函数,并且接受此类参数的构造函数不存在,因此存在错误。

thread构造函数采用函数和参数。对于成员函数,第一个参数是this指针。因此,对于您的代码,您需要:

thread rt0 { &RowChecker::check, &r0 };

那将RowChecker::check r0

.