如何在类中进行 c++ 多线程处理(将线程引用保留为成员 var)
How to do c++ multithreading in a class (keep thread ref as member var)
所以我正在尝试在c ++中做一些多线程,我正在尝试使用std::thread
。我在互联网上可以找到的所有示例都使用 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++是自上而下的解析,因为您的threadStartup函数是在您使用后声明的,因此编译器找不到它。在使用它之前声明 threadStartup,你应该没问题。
相关文章:
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- condition_variable、引用和线程:谁拥有锁?
- 启动类函数作为失去引用的线程
- 将常量引用传递给线程
- 线程安全的引用计数队列C++
- 具有对象的右值引用的线程
- C++11 多线程,通过引用传递
- C++ 线程函数通过引用传递
- C 11线程汇编错误传递字符串作为复制的引用
- C++ 11 您可以通过不同线程中的引用安全地传递和访问 std::atomics 吗?
- 通过引用将变量传递给多个线程会损坏堆
- 线程函数中的通用引用
- 通过引用和多线程传递对象
- 如何在类中进行 c++ 多线程处理(将线程引用保留为成员 var)
- 为线程构造函数传递引用以将其绑定到函数失败
- 通过在引用线程对象来传递取消引用的“this”指针来在函数对象构造函数中创建线程是好是坏
- 对抽象类的引用不能传递给线程函数?
- std::线程传递向量元素(按引用)
- 取消引用指向不同线程中的原子对象的只读非原子指针是否安全
- 引用计数类和多线程