如何在类中进行 c++ 多线程处理(将线程引用保留为成员 var)

How to do c++ multithreading in a class (keep thread ref as member var)

本文关键字:引用 线程 保留 var 成员 多线程处理 c++      更新时间:2023-10-16

所以我正在尝试在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,你应该没问题。