C++ C++;11线程-从类内部启动无限工作线程
我想提供一个类,它在读取某些数据(udp数据包或文件)时保存缓冲区。如果我从主线程开始,一切都很好,但在这种情况下,我希望避免用户必须为自己设置一个新线程 下面是我的代码,尽可能简单:C++ C++;11线程-从类内部启动无限工作线程,c++,multithreading,class,infinite,C++,Multithreading,Class,Infinite,我想提供一个类,它在读取某些数据(udp数据包或文件)时保存缓冲区。如果我从主线程开始,一切都很好,但在这种情况下,我希望避免用户必须为自己设置一个新线程 下面是我的代码,尽可能简单: class DataCollector { void startCollect() { std::thread t1(readSource); } bool readSource() { while(1) {
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;
}
//ringbuffertest.cpp:Definiert den Einstiegspunkt für die Konsolenanwendung。
//
#包括“stdafx.h”
#包括
#包括
类数据采集器
{
私人:
//线程采集器线程;
公众:
DataCollector(){}
void startCollect()
{
readSource();
}
bool readSource()
{
而(1)
{
printf(“您好,来自readSource!\n”);
睡眠(1000);
}
返回false;
}
};
int _tmain(int argc,_TCHAR*argv[]
{
数据收集器myDataCollector;
std::线程t1(&DataCollector::startCollect,std::ref(myDataCollector));
t1.join();
返回0;
}
但正如我所说,我想将线程调用隐藏在startCollect函数中。在销毁活动的
线程
对象之前,它必须被连接(等待线程完成,然后清理其资源)或分离(让它运行并在完成后清理自身)
因此,您可以将线程设置为成员变量,以便以后可以将其联接:
void startCollect()
{
this->thread = std::thread(&DataCollector::readSource, this);
}
void waitForCollectToFinish()
{
this->thread.join();
}
或者,如果您不需要等待它完成,您可以将其分离,并使用其他方式表示数据可用:
void startCollect()
{
std::thread([this]{readSource();}).detach();
}
您还可以查看更高级别的并发功能,例如
std::async
和std::future
。这可能比直接处理线程更方便。线程不应该是DataCollector的属性吗?然后你可以在构造函数中实例化它,并在startCollect中启动它。你需要有一个(或两个)缓冲区,并使用condition_变量通知每个线程有一个线程提供了一些数据。是的,我知道我的缓冲区。为了使程序尽可能简单,我把程序中的所有东西都扔掉了。你可以在上看到这个方法的作用。this->thread=std::thread(readSource,this);获取编译器错误。我将编辑一个工作示例(从main开始线程)。@user3783662:没错,它应该是&DataCollection::readSource
。或者,可能更可读的是lambda[this]{readSource();}
。