[英]Is standard guarantee safe usage of std::future after moving std::packaged_task?
[英]Is it safe to never retrieve the result of a std::future from a std::packaged_task?
從std::packaged_task
創建一個std::future
是安全的,它在一個單獨的線程上執行,但並不總是檢索它的結果?
#include <future>
#include <thread>
class Result {
Result() {}
~Result() {}
};
void foo() {
std::packaged_task<Result()> task(..);
auto future = task.get_future();
std::thread thread(std::move(task), ...);
thread.detach();
if (future.wait_for(std::chrono::milliseconds(timeout_ms)) == std::future_status::ready) {
auto result = future.get(); <--- Task didn't take too long, retrieve future result
...
}
} <--- Task is taking too long, just abort and never call future.get()
它似乎適用於Clang / libc ++: ~Result()
在std::packaged_task
返回的結果調用了~Result()
或者最終在std::future
上調用了get()
,但是因為我找不到任何東西關於這種使用模式的C ++文檔,我想確保它得到官方支持。
這取決於你認為對你的程序安全的內容。
對於您展示的上下文,它在以下情況下是安全的:
future
做一個破壞之前get
它。 如果未來是使用std::async
創建的,並且如果在銷毀之前沒有調用get
,那么它將被阻塞直到結果可用。 這些操作不會阻止共享狀態准備就緒,除非它可能阻塞以下所有條件都是真的:共享狀態是通過調用std :: async創建的,共享狀態尚未就緒,這是是共享狀態的最后一個引用。
現在,如果Result
類持有非擁有內存(無論出於何種原因)或需要手動釋放的其他資源,該怎么辦? 在這種情況下,代碼的正確性變得有問題。 最好的辦法是將它分配給一些后台線程,以便緩慢移動任務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.