【发布时间】:2022-06-27 23:01:10
【问题描述】:
所以我有以下 c++ 类,它将 std::thread 作为成员变量存储,并在该单独线程中启动成员函数。但是,此代码仅在 Visual Studio 代码中构建(使用 msys2 12.1.0 作为 G++ 编译器),当我尝试在 Visual Studio 代码中构建它时会导致错误。
导致错误的行似乎是:foo_thread = std::thread(threadFunction, this);
在 Visual Studio 代码中,我收到一条红色下划线警告,说“没有构造函数实例 std::thread::thread”与参数列表匹配”,但是代码仍然可以编译并运行良好。
在 Visual Studio 中,我收到相同的错误,并出现警告“C3867 'Foo::threadFunction': non-standard syntax; use '&' to create a pointer to member”,并且代码无法编译。当我尝试foo_thread = std::thread(&threadFunction, this); 时,错误消失了,但是当我尝试构建时,我得到错误“&:对绑定成员函数表达式的非法操作。foo_thread = std::thread(&threadFunction, this); 仍然编译并运行然而,Visual Studio 代码。
如何使本节按需要工作并能够跨 c++ 编译器/ide 进行编译?还值得一提的是,当传递给新生成的线程的函数不是成员函数时,我似乎没有收到这些错误,但是我需要它成为该程序的成员函数。
代码:
#include <thread>
#include <windows.h>
#include <iostream>
#define DllExport __declspec( dllexport )
typedef void (*funcPtr)(int num);
class Foo {
public:
// Value Constructor
Foo(int a, int b, funcPtr f) {
foo = a;
bar = b;
myFunc = f;
}
int getFoo() { return foo; };
int addBar(int a) { return private_method(a); };
void callMyFunc(int n) { myFunc(n); };
// Start Monitor
void StartThread();
// Stop Monitor
// IsMonitoring()
~Foo() {
if (foo_thread.joinable()) {
foo_thread.join();
}
};
private:
int private_method(int a) { return a + bar; };
int foo;
int bar;
std::thread foo_thread;
void threadFunction();
funcPtr myFunc;
std::atomic<bool> monitoring = ATOMIC_VAR_INIT(false);
};
void Foo::StartThread() {
foo_thread = std::thread(threadFunction, this);
}
void Foo::threadFunction() {
for (int i = 0; i < 10; i++) {
std::cout << "Hello:" << i << std::endl;
Sleep(500);
}
}
【问题讨论】:
-
typedef void (*funcPtr)(int num);-- 这是指向“常规”函数的指针的 typedef。这与指向非静态成员函数的指针不兼容(签名不同)。 -
您正在寻找的语法是
&Foo::threadFunction,有无数重复的问题,但我现在无法搜索它们。 “代码仍然可以编译并运行良好”我以某种方式怀疑它,但无论对你有用。 -
这能回答你的问题吗? Start thread with member function
标签: c++ multithreading visual-studio visual-studio-code stdthread