[英]Run loop in `std::future` until destruction - idiomatic way?
我希望成員std::future<void>
連續調用循環內的函數,直到父對象被銷毀。
我當前的解決方案涉及將未來包裝在具有布爾標志的類中,並在銷毀時將標志設置為false。
class Wrapper
{
std::future<void> fut;
bool wrapperAlive{true};
public:
Wrapper() : fut{std::async(std::launch::async, [this]
{
while(wrapperAlive) doSomething();
})} { }
~Wrapper()
{
wrapperAlive = false;
}
};
有沒有更慣用的方法呢?
這是您的代碼的免費數據版本:
class Wrapper {
std::atomic<bool> wrapperAlive{true}; // construct flag first!
std::future<void> fut;
public:
Wrapper() :
fut{std::async(std::launch::async, [this]
{
while(wrapperAlive)
doSomething();
}
)}
{}
~Wrapper() {
wrapperAlive = false;
fut.get(); // block, so it sees wrapperAlive before it is destroyed.
}
};
接下來我要做的就是寫:
template<class F>
struct repeat_async_t {
F f;
// ...
};
using repeat_async = repeat_async_t<std::function<void()>>;
template<class F>
repeat_async_t<std::decay_t<F>> make_repeat_async(F&&f){
return {std::forward<F>(f)};
}
這需要一個任務永遠重復,並將其捆綁在那里,而不是將流邏輯與執行的邏輯混合。
此時,我們可能希望添加一個中止方法。
最后,忙於循環一個線程是一個很好的主意。 因此,我們將添加某種等待更多數據消費系統。
最終看起來與你的代碼有很大的不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.