目前,我的应用程序定期调用 REST API,我正在使用一个专用线程来执行此操作(request() 是一个对象的方法):
void MyObject::request() {
while (m_continue) {
//API call, printing response, then sleeping 30 secs
usleep(30*1000);
}
}
然后制作一个像这样的线程:
thread t(&MyObject::request, this);
t.detach();
但是使用 c++11 或 Boost,使用一个不断循环的线程是否比使用多个连续的线程/异步函数更好?
像这样:
string MyObject::request() {
//API call, printing response
}
然后像下面这样多次调用它,每次都使用 future 的结果并异步调用 request():
while (m_continue) {
future<string> f = async(request);
cout << f.get() << endl;
usleep(30*1000);
}
最佳答案
是的,使用“一个不断循环的线程”。由于 std::async
,您会有相当大的开销.您将一直在调用 std::async
时创建一个新线程.
因此最好只创建一次,然后定期调用您的 API。
“<future>
”类、函数等,如std::async
, 有很棒的任务并行化接口(interface),但在幕后他们使用内核线程(就像 std::thread
一样),这意味着 pthreads
或 Windows 线程或平台提供的任何内容。因此,它们对于周期性发生的事情不是很有用,一旦您一直在创建线程并且它会产生相当大的成本。
这是来自 CppCon 2014 的非常好的视频,其中包含详细信息和基准: https://www.youtube.com/watch?v=5xyztU__yys
--
顺便说一句,与你的问题无关,但为什么不使用 this_thread::sleep_for()
? :-)
void MyObject::request() {
while (m_continue) {
//API call, printing response, then sleeping 30 secs
this_thread::sleep_for(chrono::seconds(30));
}
}
关于c++ - 更好的做法 : Ever looping thread or successive threads?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44124080/