如何调试此C 11线程代码



我最近开始在C 11中编码。由于我了解理论部分,因此我想到了通过编写代码进行实验。这是我在C 中的第一个程序,它的作用是:

我正在创建一个具有线程类型成员和2个成员函数的类,其中一个是线程函数,另一个是启动此线程函数的函数。但是我面临以下错误。我做了很多谷歌搜索,但它们都没有帮助。我想产生" Runthread"的2个线程,它们将更新counter。我知道counter没有同步,但是一旦解决此错误,我将使用std::atomic变量来处理。

#include <iostream>
#include <stdio.h>
#include <thread>
#include <vector>
class Application {
public:
    Application(int val): counter(val) { printf("value is %dn", counter); }
    void start();
    void print();
private:
    void runThread();
    int counter;
    std::vector<std::thread> thr;
};
void Application::runThread() {
    for(int i=0;1<50;i++)
        counter++;
}
void Application::start() {
    //std::thread t1(runThread);
    //std::thread t2(runThread);
    //this->thr.emplace_back(std::thread(&Application::runThread, this)); Tried this, but dint work
    //this->thr.emplace_back(std::thread(&Application::runThread, this));Tried this, but dint work
    thr.emplace_back(std::thread(runThread));
    thr.emplace_back(std::thread(runThread));
}
void Application::print() {
    printf("Counter = %dn", counter);
}
int main(void)
{
    int a;
    Application app(300);
    app.start();
    std::cin >>a;
}

这是错误

../main.cpp: In member function ‘void Application::start()’:
../main.cpp:27:40: error: invalid use of non-static member function
  thr.emplace_back(std::thread(runThread));
                                        ^
../main.cpp:28:40: error: invalid use of non-static member function
  thr.emplace_back(std::thread(runThread));
                                        ^
subdir.mk:18: recipe for target 'main.o' failed
make: *** [main.o] Error 1

编译器给您一个提示,您使用的功能是non-static,应该。这是因为在C 中,即使您看不到每个类不静态的类成员函数都会获得一个附加参数,该参数是您可能熟悉的this指针,但该指针指的是该函数然后操作的对象。因此,您的runThread()函数实际上可以被视为runThread(Application* this),这意味着std::thread构造函数不知道您想要为该参数提供的值,并期望您将其提供给它,而不是为其提供静态成员函数,该功能采用零参数。<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

一种解决方案是使runThread()静态并从全局变量(NON-NO(获取实例,或者实际告诉std::thread()构造函数该参数是什么

std::thread(&Application::runThread, this)

runThread是一个非静态成员函数,这意味着无法通过参考传递。相反,它必须包裹。

替换

thr.emplace_back(std::thread(runThread));

thr.emplace_back([this]() {this->runThread();});

另请参见:C 将指针传递给非静态成员函数

您需要包装呼叫,使用lambda

std::thread([this](){this->runThread();})

或绑定功能:

std::bind(&Application::runThread, this)

运行示例

最新更新