【问题标题】:How to do c++ multithreading in a class (keep thread ref as member var)如何在一个类中执行 C++ 多线程(将线程引用保持为成员 var)
【发布时间】:2017-11-07 15:22:47
【问题描述】:

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

【问题讨论】:

  • 要么在myClass::myClass() 之前插入threadStartup() 的原型,要么只是将整个函数向上移动。
  • 刚刚尝试过,给了我更多错误,如我的编辑中所述:(。感谢您的快速回复。
  • 如果您希望threadStartup 成为该类的一部分,请将其设为static,否则,只需修复@Scheff 提到的声明顺序即可。如果在那之后您遇到其他错误,请更新您的问题 - 它们可能与您发布的 sn-p 无关。

标签: c++ multithreading class stdthread


【解决方案1】:

无法复制。请看我的示例代码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(因为在这种情况下没有必要)。

【讨论】:

  • 我现在可以使用它了,谢谢。在我将函数向上移动后,我忘记读取我为测试目的而删除的参数。
【解决方案2】:

C++ 是自上而下解析的,因为你的 threadStartup 函数是在你使用后声明的,编译器找不到它。在使用前声明 threadStartup 应该没问题。

【讨论】:

    猜你喜欢
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多