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

我想提供一个类,该类在读取某些数据(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中调用此线程?

edit1:这是我现在的工作方式示例!

// 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对象之前,必须将其连接(等待线程完成,然后清理其资源)或分离(离开运行,并在完成后自行清理)。

因此,您可以使线程成为成员变量,以便以后可以将其加入:

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

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

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章