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创建的会阻塞。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值