c++面试输出一个线程池

面试输出一个 线程池

视频讲解输出

#pragma once

#include <thread>
#include <functional>
#include <vector>
#include <queue>
#include <mutex>
#include <atomic>
#include <condition_variable>

namespace yixiao
{
   
    /**
     * @brief 线程池
     *
     * 1.实现自旋锁队列
     * 2.使用条件变量 实现 信号量
     * 3.实现ThreadPool
     *
     */

    template <typename T>
    class SpinLockQueue
    {
   
    public:
        void Push(T &&value)
        {
   
            // lock
            while (std::atomic_flag_test_and_set_explicit(&spin_lock_, std::memory_order_acquire))
                ;
            queue_.push(std::move(value));
            // unlock
            std::atomic_flag_clear_explicit(&spin_lock_, std::memory_order_release);
        }
        std::optional<T> Pop()
        {
   
            // lock
           
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,下面是一个简单的 C++11 线程池实现,仅供参考: ```c++ #include <vector> #include <queue> #include <thread> #include <mutex> #include <condition_variable> #include <functional> #include <future> class ThreadPool { public: ThreadPool(size_t threads) : stop(false) { for (size_t i = 0; i < threads; ++i) { workers.emplace_back([this] { for (;;) { std::function<void()> task; { std::unique_lock<std::mutex> lock(this->queue_mutex); this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); }); if (this->stop && this->tasks.empty()) return; task = std::move(this->tasks.front()); this->tasks.pop(); } task(); } }); } } ~ThreadPool() { { std::unique_lock<std::mutex> lock(queue_mutex); stop = true; } condition.notify_all(); for (std::thread &worker : workers) worker.join(); } template<class F, class... Args> auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { using return_type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...)); std::future<return_type> res = task->get_future(); { std_lock<std::mutex> lock(queue_mutex); if (stop) throw std::runtime_error("enqueue on stopped ThreadPool"); tasks.emplace([task] { (*task)(); }); } condition.notify_one(); return res; } private: std::vector<std::thread> workers; std::queue<std::function<void()>> tasks; std::mutex queue_mutex; std::condition_variable condition; bool stop; }; ``` 使用方法: ```c++ #include <iostream> #include <chrono> #include <random> ThreadPool pool(4); int main() { std::vector<std::future<int>> results; for (int i = 0; i < 8; ++i) { results.emplace_back( pool.enqueue([](int num) { std::cout << "Starting task " << num << std::endl; std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dist(1000, 5000); std::this_thread::sleep_for(std::chrono::milliseconds(dist(gen))); std::cout << "Task " << num << " completed" << std::endl; return num; }, i) ); } for (auto &&result : results) std::cout << result.get() << ' '; std::cout << std::endl; return 0; } ``` 该例子会创建线程池,然后添加 8 个任务到线程池中并等待它们完成。每个任务会随机睡眠一段时间然后输出一些信息。 注意:本例子没有对异常进行处理,如果需要更完整的线程池实现需要添加异常处理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_Yi_Xiao

来瓶可乐

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值