40

次のコードがあります。

#include <iostream>
#include <future>
#include <chrono>
#include <thread>

using namespace std;

int sleep_10s()
{
    this_thread::sleep_for(chrono::seconds(10));
    cout << "Sleeping Done\n";
    return 3;
}

int main()
{
    auto result=async(launch::async, sleep_10s);
    auto status=result.wait_for(chrono::seconds(1));
    if (status==future_status::ready)
        cout << "Success" << result.get() << "\n";
    else
        cout << "Timeout\n";
}

これは、1 秒待機し、「タイムアウト」を出力して終了するはずです。終了する代わりに、さらに 9 秒間待機し、"Sleeping Done" を出力してから segfault を実行します。フューチャーの実行が完了するのを待つのではなく、メインの最後でコードが終了するように、フューチャーをキャンセルまたはデタッチする方法はありますか?

4

3 に答える 3

30

C ++ 11標準は、で開始されたタスクをキャンセルする直接的な方法を提供していませんstd::async。定期的にチェックされる非同期タスクにアトミックフラグ変数を渡すなど、独自のキャンセルメカニズムを実装する必要があります。

ただし、コードはクラッシュしないはずです。の終わりに達すると、main保持されているstd::future<int>オブジェクトresultが破棄され、タスクが終了するのを待ってから結果を破棄し、使用されているリソースをすべてクリーンアップします。

于 2012-08-23T07:56:59.743 に答える
24

これは、atomic bool を使用して 1 つまたは複数の先物を同時にキャンセルする簡単な例です。アトミック bool は Cancellation クラス内にラップできます (好みによって異なります)。

#include <chrono>
#include <future>
#include <iostream>

using namespace std;

int long_running_task(int target, const std::atomic_bool& cancelled)
{
    // simulate a long running task for target*100ms, 
    // the task should check for cancelled often enough!
    while(target-- && !cancelled)
        this_thread::sleep_for(chrono::milliseconds(100));
    // return results to the future or raise an error 
    // in case of cancellation
    return cancelled ? 1 : 0;
}

int main()
{
    std::atomic_bool cancellation_token;
    auto task_10_seconds= async(launch::async, 
                                long_running_task, 
                                100, 
                                std::ref(cancellation_token));
    auto task_500_milliseconds = async(launch::async, 
                                       long_running_task, 
                                       5, 
                                       std::ref(cancellation_token));
// do something else (should allow short task 
// to finish while the long task will be cancelled)
    this_thread::sleep_for(chrono::seconds(1));
// cancel
    cancellation_token = true;
// wait for cancellation/results
    cout << task_10_seconds.get() << " " 
         << task_500_milliseconds.get() << endl;
}
于 2015-10-24T06:21:11.030 に答える