Skip to content

C++11 线程池实现:SafeQueue、工作线程与丢失唤醒缺陷 ​

线程池解决的问题是避免为每个短任务各起一条线程:预先创建固定数量的工作线程,任务经线程安全队列分发,工作线程循环取任务执行。本文以 mtrebi/thread-pool 的早期版本为样本,拆解一个典型 C++11 线程池的三块结构——安全队列、工作线程循环、submit 的 future 封装——并分析这个版本里一个值得所有手写线程池警惕的缺陷:无谓词 wait 导致的丢失唤醒。适合想理解线程池内部机制、或准备在生产中使用此类自研实现的 C++ 开发者。

1 整体结构 ​

三块组件各司其职:

  • SafeQueue:std::queue 外面套一层互斥锁,提供线程安全的入队出队。
  • ThreadWorker:工作线程的循环体——队列空则等待条件变量,被唤醒后出队执行。
  • submit:把任意可调用对象打包成 std::packaged_task,包装成 std::function<void()> 入队,唤醒一个工作线程,返回 std::future。

2 SafeQueue:互斥锁保护的队列 ​

cpp
#pragma once

#include <mutex>
#include <queue>

// Thread safe implementation of a Queue using an std::queue
template <typename T>
class SafeQueue {
private:
  std::queue<T> m_queue;
  std::mutex m_mutex;
public:
  bool empty() {
    std::unique_lock<std::mutex> lock(m_mutex);
    return m_queue.empty();
  }

  int size() {
    std::unique_lock<std::mutex> lock(m_mutex);
    return m_queue.size();
  }

  void enqueue(T& t) {
    std::unique_lock<std::mutex> lock(m_mutex);
    m_queue.push(t);
  }

  bool dequeue(T& t) {
    std::unique_lock<std::mutex> lock(m_mutex);

    if (m_queue.empty()) {
      return false;
    }
    t = std::move(m_queue.front());
    m_queue.pop();
    return true;
  }
};

每个操作都持有 m_mutex,读写不会撕裂;dequeue 用返回值区分空队列与成功取出。

3 ThreadPool:工作线程与 submit ​

cpp
#pragma once

#include <functional>
#include <future>
#include <mutex>
#include <queue>
#include <thread>
#include <utility>
#include <vector>

#include "SafeQueue.h"

class ThreadPool {
private:
  class ThreadWorker {
  private:
    int m_id;
    ThreadPool * m_pool;
  public:
    ThreadWorker(ThreadPool * pool, const int id)
      : m_pool(pool), m_id(id) {
    }

    void operator()() {
      std::function<void()> func;
      bool dequeued;
      while (!m_pool->m_shutdown) {
        {
          std::unique_lock<std::mutex> lock(m_pool->m_conditional_mutex);
          if (m_pool->m_queue.empty()) {
            m_pool->m_conditional_lock.wait(lock);   // <-- 缺陷点,见第 5 节
          }
          dequeued = m_pool->m_queue.dequeue(func);
        }
        if (dequeued) {
          func();
        }
      }
    }
  };

  bool m_shutdown;
  SafeQueue<std::function<void()>> m_queue;
  std::vector<std::thread> m_threads;
  std::mutex m_conditional_mutex;
  std::condition_variable m_conditional_lock;
public:
  ThreadPool(const int n_threads)
    : m_threads(std::vector<std::thread>(n_threads)), m_shutdown(false) {
  }

  ThreadPool(const ThreadPool &) = delete;
  ThreadPool(ThreadPool &&) = delete;
  ThreadPool & operator=(const ThreadPool &) = delete;
  ThreadPool & operator=(ThreadPool &&) = delete;

  // Inits thread pool
  void init() {
    for (int i = 0; i < m_threads.size(); ++i) {
      m_threads[i] = std::thread(ThreadWorker(this, i));
    }
  }

  // Waits until threads finish their current task and shutdowns the pool
  void shutdown() {
    m_shutdown = true;
    m_conditional_lock.notify_all();

    for (int i = 0; i < m_threads.size(); ++i) {
      if(m_threads[i].joinable()) {
        m_threads[i].join();
      }
    }
  }

  // Submit a function to be executed asynchronously by the pool
  template<typename F, typename...Args>
  auto submit(F&& f, Args&&... args) -> std::future<decltype(f(args...))> {
    // Create a function with bounded parameters ready to execute
    std::function<decltype(f(args...))()> func = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
    // Encapsulate it into a shared ptr in order to be able to copy construct / assign
    auto task_ptr = std::make_shared<std::packaged_task<decltype(f(args...))()>>(func);

    // Wrap packaged task into void function
    std::function<void()> wrapper_func = [task_ptr]() {
      (*task_ptr)();
    };

    // Enqueue generic wrapper function
    m_queue.enqueue(wrapper_func);

    // Wake up one thread if its waiting
    m_conditional_lock.notify_one();

    // Return future from promise
    return task_ptr->get_future();
  }
};

几处实现细节值得注意:

  • std::packaged_task 必须套进 std::shared_ptr:packaged_task 是 move-only 的,而 std::function 要求可拷贝构造,直接包会编译失败。套一层 shared_ptr 让 lambda 变成可拷贝的。
  • submit 返回的 future 由 packaged_task 自动满足:任务在工作线程执行完,future 就绪;任务抛出的异常同样经 future 传递,不会直接 terminate。
  • shutdown 的顺序:先置 m_shutdown 再 notify_all,工作线程从 wait 中醒来后因循环条件退出,逐个 join。

4 使用示例 ​

cpp
#include <iostream>
#include <random>

#include "ThreadPool.h"

std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> dist(-1000, 1000);
auto rnd = std::bind(dist, mt);

void simulate_hard_computation() {
  std::this_thread::sleep_for(std::chrono::milliseconds(2000 + rnd()));
}

void multiply(const int a, const int b) {
  simulate_hard_computation();
  const int res = a * b;
  std::cout << a << " * " << b << " = " << res << std::endl;
}

void multiply_output(int & out, const int a, const int b) {
  simulate_hard_computation();
  out = a * b;
  std::cout << a << " * " << b << " = " << out << std::endl;
}

int multiply_return(const int a, const int b) {
  simulate_hard_computation();
  const int res = a * b;
  std::cout << a << " * " << b << " = " << res << std::endl;
  return res;
}

int main(int argc, char *argv[])
{
  ThreadPool pool(3);
  pool.init();

  // 提交一批无返回值任务
  for (int i = 1; i < 3; ++i) {
    for (int j = 1; j < 10; ++j) {
      pool.submit(multiply, i, j);
    }
  }

  // 引用参数输出:std::ref 传入
  int output_ref;
  auto future1 = pool.submit(multiply_output, std::ref(output_ref), 5, 6);
  future1.get();
  std::cout << "Last operation result is equals to " << output_ref << std::endl;

  // 返回值经 future 取回
  auto future2 = pool.submit(multiply_return, 5, 3);
  int res = future2.get();
  std::cout << "Last operation result is equals to " << res << std::endl;

  pool.shutdown();
  return 0;
}

5 丢失唤醒:无谓词 wait 的缺陷 ​

工作线程循环里的这一行是本实现最大的隐患:

cpp
m_pool->m_conditional_lock.wait(lock);

condition_variable::wait(lock) 的无谓词版本阻塞直到被 notify。问题在于 notify 不排队、不留痕:如果 notify 到达时目标线程还没有进入等待状态,这次唤醒就永远丢失了。

竞态时序 ​

这个实现里,检查队列与进入等待之间存在窗口:

工作线程                                submit 线程
--------                                -----------
lock(m_conditional_mutex)
检查 m_queue.empty() == true
(尚未进入 wait)
                                        enqueue(wrapper_func)   ← 持 SafeQueue 自己的锁
                                        notify_one()            ← 不需要 m_conditional_mutex
进入 wait(lock),阻塞
—— 此后再无 notify,任务滞留队列

关键在于 submit 的 notify_one 不获取 m_conditional_mutex,因此它可以在工作线程「检查完队列为空」与「进入 wait」之间插入。窗口极小,但在高频率提交的场景下迟早命中:表现为任务明明已入队,却没有线程来执行,直到下一次 submit 的 notify 碰巧唤醒它。此外,无谓词 wait 也防不住伪唤醒(spurious wakeup)——条件变量允许在没有 notify 的情况下醒来。

上游仓库 master 分支后来已把等待改为谓词版本。标准修法是把「条件检查」交给 wait 自己,用循环条件做谓词:

cpp
std::unique_lock<std::mutex> lock(m_pool->m_conditional_mutex);
m_pool->m_conditional_lock.wait(lock, [this] {
    return m_pool->m_shutdown || !m_pool->m_queue.empty();
});
dequeued = m_pool->m_queue.dequeue(func);

谓词版本的 wait 等价于「while (!pred()) wait(lock);」:被唤醒后重新检查条件,条件不满足继续睡;条件满足(有任务或要关闭)才返回。检查与阻塞在 wait 内部原子化,notify 插在中间也会被下一次条件检查看见,丢失唤醒与伪唤醒同时解决。

这也是使用条件变量的通用准则:永远用谓词版本的 wait(或手写 while 循环重查),把共享条件的判定和等待绑在一起,不要裸调无谓词 wait。

6 其他两点 ​

  1. 析构没有兜底 shutdown:这个版本忘了调用 shutdown() 的话工作线程未 join,std::thread 析构时程序直接 std::terminate。健壮的做法是在析构函数里兜底调用一次 shutdown。
  2. std::bind + std::function 的类型擦除开销:submit 用 std::bind 绑参数再装进 std::function,有一次堆分配与间接调用开销,且 std::bind 对 move-only 参数(如 unique_ptr)支持很差。现代实现可以直接把调用包进 move-only lambda,配合 packaged_task 使用。

7 要点 ​

  • 线程池三件套:互斥队列分发任务、工作线程循环「等待—取任务—执行」、submit 打包 packaged_task 返回 future。
  • packaged_task 是 move-only,装进 std::function 前需要 shared_ptr 包一层。
  • 条件变量等待必须带谓词:无谓词 wait 存在「检查与阻塞之间」的丢失唤醒窗口,notify 不获取检查方持有的锁时窗口无法关闭;谓词把检查纳入 wait 内部,同时防住伪唤醒。
  • 线程池收尾要兜底:析构中确保 shutdown + join,否则 std::thread 析构直接 terminate。
最近更新

基于 VitePress 构建