簡體   English   中英

std :: async和std :: shared_future導致程序崩潰

[英]std::async and std::shared_future causes the program to fall

我正在嘗試以異步方式運行某些功能。 為此,我編寫了一個名為Core類,在其中我使用std::async在不同線程中運行函數,並使用std::shared_future<int>等待該線程並可能獲得未來的結果。 這是測試程序的代碼

#include <iostream>
#include <future>

class Core : public std::enable_shared_from_this<Core>
{
public:
    Core()
        : isRunning_(false) {
    };
    ~Core() {
        isRunning_ = false;
        if (f_.valid())
        {
            f_.wait();
            std::cout << "Result is: " << f_.get() << std::endl;
        }
    };
    void Start() {
        isRunning_ = true;
        auto self(shared_from_this());
        f_ = std::async(std::launch::async, [self, this]() {
            try {
                while (true) {
                    if (!isRunning_)
                        break;

                    std::cout << "Boom" << std::endl; // Error occurs here
                    std::this_thread::sleep_for(std::chrono::seconds(1));
                }
            }
            catch (const std::exception& e) {
                std::cerr << "Loop error:" << e.what();
            }
            return 999;
        });
    }

private:
    std::shared_future<int> f_;
    std::atomic<bool> isRunning_;
};

int main()
{
    try {
        std::shared_ptr<Core> load(new Core);
        load->Start();

        throw std::runtime_error("Generate error"); // Added in order to generate error
    }
    catch (const std::exception& e) {
        std::cout << "Error occurred: " << e.what();
    }

    return 0;
}

每次我啟動該程序時,它都會在此行崩潰:

std::cout << "Boom" << std::endl; // Error occurs here

出現此錯誤:

錯誤輸出

那是我在調試期間設法獲得的調試器錯誤和調用堆棧:

在此處輸入圖片說明

看起來Core析構函數根本沒有調用。 為什么會這樣呢? 奇怪的!!!

你能告訴我我的錯誤在哪里嗎? 謝謝。

當主線程從main()返回時,它開始拆除環境,然后終止整個過程。 在后台線程訪問對象時,所有這些都已被破壞或已經被破壞。

我不確定您要達到的目標,但您做錯了什么:

  • 您的lambda應該執行一些工作並在完成后立即返回,例如,您永遠不要永遠循環。
  • 您的主線程應通過調用std::future<T>::get()等待您的將來完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM