std::future 注意點

  std::future是一個線程裏面異步獲取值的類,在使用時有一些注意點。最近照着網上寫了一個線程池

#pragma once

#include <vector>
#include <queue>
#include <thread>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>

namespace std
{
#define MAX_THREAD_NUM 256
class threadpool
{
public:
    inline threadpool(unsigned short size = 4) : stoped(false)
    {
        idlThrNum = size < 1 ? 1 : size;
        for (size = 0; size < idlThrNum; ++size)
        {
            pool.emplace_back([this] {
                while (!stoped)
                {
                    std::function<void()> task;
                    {
                        std::unique_lock<std::mutex> lock(m_lock);
                        cv_task.wait(lock, [this] { return stoped.load() || !tasks.empty(); });
                        if (!stoped.load() && !tasks.empty())
                        {
                            task = std::move(tasks.front());
                            tasks.pop();
                        }else{
                            continue;
                        }
                    }
                    idlThrNum--;
                    task();
                    idlThrNum++;
                }
                idlThrNum--;
            });
        }
    }

    inline ~threadpool()
    {
        stoped.store(true);
        cv_task.notify_all();
        for (std::thread &t : pool)
        {
            if (t.joinable())
            {
                t.join();
            }
        }
    }

    template <typename F, typename... Args>
    auto commit(F &&f, Args &&... args) -> std::future<decltype(f(args...))>
    {
        if (stoped.load())
        {
            throw std::runtime_error("commit on Threadpool is stopped");
        }

        using RetType = decltype(f(args...));
        auto task = std::make_shared<std::packaged_task<RetType()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
        std::future<RetType> future = task->get_future();
        {
            std::lock_guard<std::mutex> lock(m_lock);
            tasks.emplace([task] {
                (*task)();
            });
        }
        cv_task.notify_one();

        return future;
    }

    int idlCount() { return idlThrNum; }

private:
    using Task = std::function<void()>; //任務函數
    std::vector<std::thread> pool;      //線程池
    std::queue<Task> tasks;             //任務隊列
    std::mutex m_lock;                  //互斥鎖
    std::condition_variable cv_task;    //條件阻塞
    std::atomic<bool> stoped;           //是否關閉提交
    std::atomic<int> idlThrNum;         //空閒線程數量
};
} // namespace std

測試代碼如下

    try
    {
        std::threadpool pool(std::thread::hardware_concurrency() * 2);
        {
            std::future<void> result = pool.commit([] {
                unsigned long long total = 0;
                for (int i = 0; i < 5; i++)
                {
                    std::this_thread::sleep_for(std::chrono::seconds(1));
                    std::cout << "task execute" << std::endl;
                }
                std::cout << "task finished" << std::endl;
            });
            // result.get();
        }
        std::cout << "main thread going" << std::endl;
        char c = ::getchar();
    }
    catch (const std::exception &e)
    {
        std::cout << e.what() << std::endl;
    }

此時std::future並沒有因爲析構阻塞,commit後直接主函數就打印了main thread going。

另外一段測試代碼如下

    {
    std::future
    若返回對象或提供方保有到其共享狀態的最後引用,則析構共享狀態;
    返回對象或提供方放棄到其共享狀態的引用;
    這些動作將不會阻塞至共享狀態變爲準備,除了若以下爲真則它可能阻塞:共享狀態以到 std::async 的調用創建,共享狀態仍未就緒,且 this 是到共享狀態的最後引用。

        std::future<int> result = std::async(std::launch::async, [] {
            std::this_thread::sleep_for(std::chrono::seconds(3));
            std::cout << "async finished" << std::endl;
            return 3;
        });
    }

    std::cout << "main going" << std::endl;

此時std::future就會因爲析構阻塞,經查閱資料發現,如果

    若返回對象或提供方保有到其共享狀態的最後引用,則析構共享狀態;
    返回對象或提供方放棄到其共享狀態的引用;
    這些動作將不會阻塞至共享狀態變爲準備,除了若以下爲真則它可能阻塞:共享狀態以到 std::async 的調用創建,共享狀態仍未就緒,且 this 是到共享狀態的最後引用。

所以通過std::async創建的會阻塞。

發佈了82 篇原創文章 · 獲贊 58 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章