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

标签 c++ multithreading class stdthread

所以我正在尝试在 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/

相关文章:

java - 在java中创建类的实例时遇到问题

ios - 从另一个类中的函数获取返回值

C++ __declspec( dllexport ) 函数无法访问实例变量

c++ - 有效地找到最小值和最大值

C++11 声明 `::T i` ?

c++ - 对于短共享操作和少数独特操作,是否有任何共享互斥锁的方法?

android - 等待 Activity 显示

c++ - 通过 "a pointer of the base class"访问未在基类中声明的子类的方法或属性(动态)

c++ - std::forward() 的右值引用重载的目的是什么?

java - Java 8中等待状态线程不断增加的原因是什么