我想提供一个类,它在读取某些数据(udp数据包或来自文件)时保存缓冲区。一切都很好,如果我从主开始我的线程,但在这种情况下,我想避免,用户必须为自己设置一个新的线程。C++ 11线程 - 从类内部开始无限工作线程
所以这里是我的代码那样简单我可以使它:
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函数内的线程调用。
线程不应该是DataCollector的属性吗?然后你可以在构造函数中实例化它并在startCollect中启动它。 –
您将需要一个缓冲区(或两个)并使用condition_variable通知每个线程已提供一些数据。 –
你我知道我的缓冲区。我只是从我的程序中扔出一切,使其尽可能简单。 –