C++11 线程 - 从类内部启动无限工作线程

标签 c++ multithreading class infinite

我想提供一个类,它在读取某些数据(udp 数据包或文件)时保存一个缓冲区。如果我从主线程开始我的线程,一切都很好,但在这种情况下,我想避免用户必须为自己设置一个新线程。

所以我的代码尽可能简单:

class DataCollector
{
    void startCollect()
    {
        std::thread t1(readSource);
    }

    bool readSource()
    {
        while(1)
        {
            // read some data for storage
        }
    }   
}

int main()
{
    DataCollector myDataCollector;
    myDataCollector.startCollect();

    while(1)
    {
        // do some other work, for example interpret the data
    }

    return 0;
}

现在我需要你的帮助。我如何在 startCollect 中调用这个线程?

编辑1: 这是我现在如何运作的示例!

// ringbuffertest.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//

#include "stdafx.h"
#include <thread>
#include <Windows.h>

class DataCollector
{
private:
    //std::thread collecterThread;

public:
    DataCollector(){}

    void startCollect()
    {       
        readSource();
    }

    bool readSource()
    {
        while (1)
        {
            printf("Hello from readSource!\n");
            Sleep(1000);
        }
        return false;
    }
};


int _tmain(int argc, _TCHAR* argv[])
{
    DataCollector myDataCollector;

    std::thread t1(&DataCollector::startCollect, std::ref(myDataCollector));

    t1.join();
    return 0;
}

但正如我所说,我想将线程调用隐藏在我的 startCollect 函数中。

最佳答案

在销毁事件的thread 对象之前,它必须加入(等待线程完成,然后清理其资源)或分离 em>(留下来运行并在完成后自行清理)。

所以你可以让线程成为一个成员变量,这样它就可以在以后加入:

void startCollect()
{
    this->thread = std::thread(&DataCollector::readSource, this);
}

void waitForCollectToFinish()
{
    this->thread.join();
}

或者您可以分离它,如果您不需要等待它完成的能力,并且有一些其他方式表明数据可用:

void startCollect()
{
    std::thread([this]{readSource();}).detach();
}

您还可以查看更高级别的并发工具,例如 std::asyncstd::future。这些可能比直接处理线程更方便。

关于C++11 线程 - 从类内部启动无限工作线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24455156/

相关文章:

c++ - 如何将通用 packaged_tasks 存储在容器中?

java - 继承不允许我创建子类的对象?

php - Web 浏览器未返回任何内容 - 功能错误?

c++ - 我在尝试计算涉及数组的总和和平均值时遇到问题

java - 使用多个连接下载文件

java - 如果锁本身被争用会怎样?

python - 无法访问类属性

c++ - 将 C++ 中的位交换为 double

C++构造函数问题

c++ - 使用指向函数的指针数组创建结构