std::thread 在 c++ 中设置线程函数时不能出错
std::thread in c++ cant error when setting thread function
我正在尝试在 C++ 中使用 std::thread 但没有成功:
A.h
class A
{
public:
A();
void MainThread();
Init();
private:
std::thread currThread;
}
A.cpp
A::A()
{
}
void A::Init()
{
currThread = std::thread(A::MainThread);
//currThread = std::thread(&MainThread);
}
void A::MainThread()
{
while (true)
{
std::cout << "Just For Example...");
}
}
尝试使用 MainFunction 创建线程时,Init 函数出现编译错误
我做错了什么,我该如何解决?
由于MainThread()
方法不是静态的,对于不同的对象会多次存在,所以需要说明你指的是属于this
对象的方法(对象您正在 Init()
上打电话)。
您的代码有很多令人担忧的地方(语法错误、无限循环等)。您的示例代码(带有修复程序)应如下所示:
// A.hpp
#ifndef A_HPP
#define A_HPP
#include <thread>
class A
{
public:
void Init();
void MainThread();
private:
std::thread currThread;
};
#endif // A_HPP
// A.cpp
#include <iostream>
#include <thread>
#include "A.h"
void A::Init()
{
this->currThread = std::thread(&A::MainThread, this);
}
void A::MainThread()
{
//this loop will run forever
while (true)
{
std::cout << "Just For Example...";
}
}
我正在尝试在 C++ 中使用 std::thread 但没有成功:
A.h
class A
{
public:
A();
void MainThread();
Init();
private:
std::thread currThread;
}
A.cpp
A::A()
{
}
void A::Init()
{
currThread = std::thread(A::MainThread);
//currThread = std::thread(&MainThread);
}
void A::MainThread()
{
while (true)
{
std::cout << "Just For Example...");
}
}
尝试使用 MainFunction 创建线程时,Init 函数出现编译错误
我做错了什么,我该如何解决?
由于MainThread()
方法不是静态的,对于不同的对象会多次存在,所以需要说明你指的是属于this
对象的方法(对象您正在 Init()
上打电话)。
您的代码有很多令人担忧的地方(语法错误、无限循环等)。您的示例代码(带有修复程序)应如下所示:
// A.hpp
#ifndef A_HPP
#define A_HPP
#include <thread>
class A
{
public:
void Init();
void MainThread();
private:
std::thread currThread;
};
#endif // A_HPP
// A.cpp
#include <iostream>
#include <thread>
#include "A.h"
void A::Init()
{
this->currThread = std::thread(&A::MainThread, this);
}
void A::MainThread()
{
//this loop will run forever
while (true)
{
std::cout << "Just For Example...";
}
}