【问题标题】:Proper thread call syntax? error: no matching call to std::thread::thread(<brace-enclosed initializer list>)正确的线程调用语法?错误:没有匹配的调用 std::thread::thread(<brace-enclosed initializer list>)
【发布时间】:2013-11-11 20:49:45
【问题描述】:

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

#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;
}

抱歉,篇幅过长。另外,我知道传递数组是一种很好的招致错误的方法。我打算将其转换为向量。

【问题讨论】:

    标签: c++ multithreading c++11 stdthread


    【解决方案1】:

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

    thread 构造函数接受一个函数和参数。在成员函数的情况下,第一个参数是this 指针。因此,对于您的代码,您需要:

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

    这将在r0 上调用RowChecker::check

    【讨论】:

    • 不需要调用bindthread 构造函数在这种情况下做同样的事情。
    • +1,但你最好删除绑定的东西,少一些混乱。
    • 感谢 Jay & co。读完你的第一行后,我做了一个手掌......根据你的建议,我能够编译和运行代码。
    猜你喜欢
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 2018-10-23
    • 2013-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    相关资源
    最近更新 更多