所以我正在尝试在 C++ 中做一些多线程,我正在尝试使用 std::thread
。我在 Internet 上可以找到的所有示例都使用 main 方法。但是我想在类构造函数中创建一个线程,并在析构函数中加入线程,然后清理线程。我已经尝试过一些这样的事情:
.cpp:
#inlcude "iostream"
myClass::myClass()
{
myThread= new std::thread(threadStartup, 0);
}
myClass::~myClass()
{
myThread->join();
delete myThread;
}
void threadStartup(int threadid)
{
std::cout << "Thread ID: " << threadid << std::endl;
}
.h
#pragma once
#include "thread"
class myClass
{
public:
myClass();
~myClass();
private:
std::thread* myThread;
};
这给了我以下错误错误:C2065: 'threadStartup': undeclared identifier
。我还尝试将线程启动方法添加到类中,但这给了我更多的错误。
我想不通,如有任何帮助,我们将不胜感激。
编辑:std::thread
已更改为 std::thread*
,就像我的代码中一样。
如果我将 threadStartup
的函数声明移动到我的文件的顶部,我会得到错误:
Severity Code Description Project File Line Suppression State
Error C2672 'std::invoke': no matching overloaded function found
和
Severity Code Description Project File Line Suppression State
Error C2893 Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...) noexcept(<expr>)'
最佳答案
无法重现。请看我的示例代码test-thread.cc
:
#include <iostream>
#include <thread>
class MyClass {
private:
std::thread myThread;
public:
MyClass();
~MyClass();
};
void threadStartup(int threadid)
{
std::cout << "Thread ID: " << threadid << std::endl;
}
MyClass::MyClass():
myThread(&threadStartup, 0)
{ }
MyClass::~MyClass()
{
myThread.join();
}
int main()
{
MyClass myClass;
return 0;
}
在 Windows 10(64 位)上的 cygwin64 中测试:
$ g++ --version
g++ (GCC) 5.4.0
$ g++ -std=c++11 -o test-thread test-thread.cc
$ ./test-thread
Thread ID: 0
$
请注意,我没有使用 new
(因为在这种情况下没有必要)。
关于c++ - 如何在类中进行 C++ 多线程处理(将线程引用保留为成员 var),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47161473/