CMake集成Condition Variable条件变量实现跨平台线程同步与高效并发控制

引言:理解条件变量在现代并发编程中的核心地位
在多线程编程中,线程同步是一个至关重要的概念。条件变量(Condition Variable)作为现代并发编程的核心工具之一,为线程间的协调与通信提供了高效的机制。本文将深入探讨如何在CMake项目中集成条件变量,实现跨平台的线程同步与高效并发控制。
条件变量的基本概念
条件变量是一种同步原语,它允许线程在某个条件不满足时挂起,直到另一个线程改变条件并通知它。条件变量通常与互斥锁(Mutex)配合使用,以避免竞态条件。
关键特性:
等待/通知机制
:线程可以等待某个条件成立,而其他线程可以通知条件已满足
避免忙等待
:相比轮询,条件变量让线程在等待时进入休眠状态,节省CPU资源
跨平台兼容性
:现代操作系统都提供了条件变量的实现
为什么选择CMake进行项目管理
CMake是一个广泛使用的构建系统生成器,它提供了:
跨平台支持
:一次编写,到处编译
模块化管理
:便于集成第三方库和自定义组件
现代C++标准支持
:轻松启用C++11/14/17/20标准
依赖管理
:简化复杂项目的构建过程
条件变量的底层实现原理
操作系统级别的实现差异
不同操作系统对条件变量的实现各有特点:
Windows平台:
使用
CONDITION_VARIABLE
结构体
API:
InitializeConditionVariable
,
SleepConditionVariableCS
,
WakeConditionVariable
Linux/Unix平台:
使用
pthread_cond_t
(POSIX线程库)
API:
pthread_cond_init
,
pthread_cond_wait
,
pthread_cond_signal
C++11标准库:
std::condition_variable
(头文件

)
提供了跨平台的统一接口
条件变量的工作流程
线程A (生产者) 线程B (消费者)
| |
|— 获取互斥锁 ————>|
|— 修改条件 ————->|
|— 发送通知 ————->|
|— 释放互斥锁 ————>|
| |
|<--- 获取互斥锁 -----------| |<--- 检查条件 -------------| |<--- 条件不满足,等待 -----| | | |<--- 收到通知 -------------| |<--- 重新检查条件 ---------| |<--- 条件满足,继续 -------| CMake项目结构设计 项目目录结构 condition_variable_project/ ├── CMakeLists.txt ├── include/ │ ├── thread_pool.h │ └── condition_variable_wrapper.h ├── src/ │ ├── main.cpp │ ├── thread_pool.cpp │ └── condition_variable_wrapper.cpp ├── tests/ │ └── test_condition_variable.cpp └── third_party/ └── (可选的第三方库) CMakeLists.txt 配置详解 # 最低CMake版本要求 cmake_minimum_required(VERSION 3.14) # 项目信息 project(ConditionVariableDemo VERSION 1.0.0 DESCRIPTION "跨平台条件变量线程同步演示" LANGUAGES CXX ) # 设置C++标准 set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) # 针对不同平台的编译器定义 if(WIN32) add_definitions(-DWIN32_LEAN_AND_MEAN) add_definitions(-DNOMINMAX) elseif(UNIX AND NOT APPLE) add_definitions(-D_GNU_SOURCE) endif() # 包含目录 include_directories( ${PROJECT_SOURCE_DIR}/include ${PROJECT_SOURCE_DIR}/src ) # 源文件集合 set(SOURCES src/main.cpp src/thread_pool.cpp src/condition_variable_wrapper.cpp ) # 创建可执行文件 add_executable(${PROJECT_NAME} ${SOURCES}) # 链接系统线程库 find_package(Threads REQUIRED) target_link_libraries(${PROJECT_NAME} PRIVATE Threads::Threads) # 编译器特定选项 if(MSVC) target_compile_options(${PROJECT_NAME} PRIVATE /W4 /WX) else() target_compile_options(${PROJECT_NAME} PRIVATE -Wall -Wextra -Wpedantic -Werror) endif() # 安装配置(可选) install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION bin LIBRARY DESTINATION lib ARCHIVE DESTINATION lib ) # 测试配置(启用测试) enable_testing() add_subdirectory(tests) 跨平台条件变量封装实现 头文件定义 (include/condition_variable_wrapper.h) #ifndef CONDITION_VARIABLE_WRAPPER_H #define CONDITION_VARIABLE_WRAPPER_H #include
#include
#include

// 跨平台条件变量封装类
class ConditionVariableWrapper {
public:
// 构造函数
ConditionVariableWrapper();

// 析构函数
~ConditionVariableWrapper();

// 禁用拷贝构造和赋值
ConditionVariableWrapper(const ConditionVariableWrapper&) = delete;
ConditionVariableWrapper& operator=(const ConditionVariableWrapper&) = delete;

// 等待条件满足(无限等待)
void wait(std::unique_lock& lock);

// 等待条件满足(带超时)
template
bool wait_for(std::unique_lock& lock,
const std::chrono::duration& timeout);

// 等待条件满足(到指定时间点)
template
bool wait_until(std::unique_lock& lock,
const std::chrono::time_point& timeout_time);

// 通知一个等待线程
void notify_one();

// 通知所有等待线程
void notify_all();

private:
std::condition_variable m_cond;
};

// 模板函数实现
template
bool ConditionVariableWrapper::wait_for(std::unique_lock& lock,
const std::chrono::duration& timeout) {
return m_cond.wait_for(lock, timeout) == std::cv_status::no_timeout;
}

template
bool ConditionVariableWrapper::wait_until(std::unique_lock& lock,
const std::chrono::time_point& timeout_time) {
return m_cond.wait_until(lock, timeout_time) == std::cv_status::no_timeout;
}

#endif // CONDITION_VARIABLE_WRAPPER_H
源文件实现 (src/condition_variable_wrapper.cpp)
#include “condition_variable_wrapper.h”

ConditionVariableWrapper::ConditionVariableWrapper() {
// std::condition_variable 在构造时自动初始化
}

ConditionVariableWrapper::~ConditionVariableWrapper() {
// std::condition_variable 在析构时自动清理
}

void ConditionVariableWrapper::wait(std::unique_lock& lock) {
if (!lock.owns_lock()) {
throw std::system_error(std::make_error_code(std::errc::operation_not_permitted),
“ConditionVariableWrapper::wait: lock must be held”);
}
m_cond.wait(lock);
}

void ConditionVariableWrapper::notify_one() {
m_cond.notify_one();
}

void ConditionVariableWrapper::notify_all() {
m_cond.notify_all();
}
实际应用案例:生产者-消费者模式
生产者-消费者头文件 (include/thread_pool.h)
#ifndef THREAD_POOL_H
#define THREAD_POOL_H

#include “condition_variable_wrapper.h”
#include
#include
#include #include
#include
#include

// 任务类型定义
using Task = std::function;

// 线程池类
class ThreadPool {
public:
// 构造函数:创建指定数量的工作线程
explicit ThreadPool(size_t num_threads);

// 析构函数:确保所有线程安全退出
~ThreadPool();

// 禁用拷贝
ThreadPool(const ThreadPool&) = delete;
ThreadPool& operator=(const ThreadPool&) = delete;

// 提交任务到线程池
void enqueue(Task task);

// 关闭线程池(等待所有任务完成)
void shutdown();

// 获取当前队列大小
size_t get_queue_size() const;

// 获取活跃线程数
size_t get_active_count() const;

private:
// 工作线程函数
void worker_thread();

// 任务队列
std::queue m_task_queue;

// 互斥锁保护任务队列
mutable std::mutex m_queue_mutex;

// 条件变量用于任务通知
ConditionVariableWrapper m_task_cv;

// 线程容器
std::vector m_workers;

// 原子标志:是否正在关闭
std::atomic m_shutdown{false};

// 原子计数器:当前正在执行的任务数
std::atomic m_active_tasks{0};
};

#endif // THREAD_POOL_H
线程池实现 (src/thread_pool.cpp)
#include “thread_pool.h”
#include
#include

ThreadPool::ThreadPool(size_t num_threads) {
if (num_threads == 0) {
throw std::invalid_argument(“ThreadPool must have at least one thread”);
}

// 创建工作线程
for (size_t i = 0; i < num_threads; ++i) { m_workers.emplace_back(&ThreadPool::worker_thread, this); } } ThreadPool::~ThreadPool() { shutdown(); } void ThreadPool::enqueue(Task task) { if (m_shutdown.load()) { throw std::runtime_error("Cannot enqueue task on shutdown ThreadPool"); } { std::lock_guard lock(m_queue_mutex);
m_task_queue.push(std::move(task));
}

// 通知一个等待的线程有新任务
m_task_cv.notify_one();
}

void ThreadPool::shutdown() {
// 双重检查避免重复关闭
bool expected = false;
if (!m_shutdown.compare_exchange_strong(expected, true)) {
return; // 已经关闭
}

// 通知所有等待的线程
{
std::lock_guard lock(m_queue_mutex);
// 空任务作为终止信号
m_task_queue.push([](){});
}
m_task_cv.notify_all();

// 等待所有线程完成
for (auto& worker : m_workers) {
if (worker.joinable()) {
worker.join();
}
}
}

size_t ThreadPool::get_queue_size() const {
std::lock_guard lock(m_queue_mutex);
return m_task_queue.size();
}

size_t ThreadPool::get_active_count() const {
return m_active_tasks.load();
}

void ThreadPool::worker_thread() {
while (true) {
Task task;

{
// 获取锁并等待任务
std::unique_lock lock(m_queue_mutex);

// 等待条件:有任务或关闭标志
m_task_cv.wait(lock, [this]() {
return !m_task_queue.empty() || m_shutdown.load();
});

// 检查是否关闭
if (m_shutdown.load() && m_task_queue.empty()) {
break;
}

// 获取任务
if (!m_task_queue.empty()) {
task = std::move(m_task_queue.front());
m_task_queue.pop();
}
}

// 执行任务(在锁外执行,避免阻塞其他线程)
if (task) {
m_active_tasks++;
try {
task();
} catch (const std::exception& e) {
std::cerr << "Task execution failed: " << e.what() << std::endl; } m_active_tasks--; } } } 主程序入口 (src/main.cpp) #include "thread_pool.h" #include
#include
#include
#include

// 模拟耗时任务
void simulate_work(int id, int duration_ms) {
std::this_thread::sleep_for(std::chrono::milliseconds(duration_ms));
std::cout << "Task " << id << " completed after " << duration_ms << "ms\n"; } // 计算密集型任务 void cpu_intensive_task(int id, int iterations) { volatile long long result = 0; for (int i = 0; i < iterations; ++i) { result += i * i; } std::cout << "CPU Task " << id << " finished with result: " << result << "\n"; } // 生产者-消费者演示 void producer_consumer_demo() { std::cout << "\n=== 生产者-消费者演示 ===\n"; ThreadPool pool(4); std::atomic counter{0};
const int num_tasks = 10;

// 生产者:提交任务
auto start = std::chrono::high_resolution_clock::now();

for (int i = 0; i < num_tasks; ++i) { pool.enqueue([i, &counter]() { simulate_work(i, 100); counter++; }); } // 等待所有任务完成 while (counter.load() < num_tasks) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(end – start);

std::cout << "所有任务完成,耗时: " << duration.count() << "ms\n"; std::cout << "最终计数器值: " << counter.load() << "\n"; } // 超时控制演示 void timeout_control_demo() { std::cout << "\n=== 超时控制演示 ===\n"; ThreadPool pool(2); std::atomic long_task_done{false};

// 提交一个长耗时任务
pool.enqueue([&long_task_done]() {
std::cout << "开始执行长耗时任务...\n"; std::this_thread::sleep_for(std::chrono::seconds(3)); long_task_done = true; std::cout << "长耗时任务完成\n"; }); // 主线程等待任务完成,但设置超时 auto start = std::chrono::high_resolution_clock::now(); const auto timeout = std::chrono::seconds(2); while (!long_task_done.load()) { auto now = std::chrono::high_resolution_clock::now(); if (now - start > timeout) {
std::cout << "任务执行超时!\n"; break; } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } if (long_task_done.load()) { std::cout << "任务在超时前完成\n"; } } // 批量任务处理演示 void batch_processing_demo() { std::cout << "\n=== 批量任务处理演示 ===\n"; ThreadPool pool(8); std::vector results(1000);
std::atomic completed{0};

auto start = std::chrono::high_resolution_clock::now();

// 提交1000个任务
for (int i = 0; i < 1000; ++i) { pool.enqueue([i, &results, &completed]() { // 模拟计算 int sum = 0; for (int j = 0; j < 100; ++j) { sum += j; } results[i] = sum; completed++; }); } // 等待完成 while (completed.load() < 1000) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(end – start);

// 验证结果
long long total = std::accumulate(results.begin(), results.end(), 0LL);
std::cout << "批量处理完成,耗时: " << duration.count() << "ms\n"; std::cout << "处理的任务数: " << completed.load() << "\n"; std::cout << "结果总和: " << total << "\n"; } int main() { std::cout << "=== CMake集成条件变量线程同步演示 ===\n"; std::cout << "平台: " << #ifdef _WIN32 "Windows" #elif __linux__ "Linux" #elif __APPLE__ "macOS" #else "Unknown" #endif << "\n"; try { producer_consumer_demo(); timeout_control_demo(); batch_processing_demo(); std::cout << "\n=== 所有演示完成 ===\n"; } catch (const std::exception& e) { std::cerr << "错误: " << e.what() << std::endl; return 1; } return 0; } 测试代码 (tests/test_condition_variable.cpp) #include
#include “thread_pool.h”
#include “condition_variable_wrapper.h”
#include
#include #include

// 测试基本功能
TEST(ConditionVariableTest, BasicNotification) {
ThreadPool pool(2);
std::atomic task_executed{false};

pool.enqueue([&task_executed]() {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
task_executed = true;
});

// 等待任务完成
auto start = std::chrono::high_resolution_clock::now();
while (!task_executed.load()) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
auto now = std::chrono::high_resolution_clock::now();
if (now – start > std::chrono::seconds(1)) {
break;
}
}

EXPECT_TRUE(task_executed.load());
}

// 测试超时机制
TEST(ConditionVariableTest, TimeoutMechanism) {
ConditionVariableWrapper cv;
std::mutex mtx;
std::atomic timeout_occurred{false};

std::thread t1([&]() {
std::unique_lock lock(mtx);
auto timeout = std::chrono::milliseconds(100);
auto result = cv.wait_for(lock, timeout);
timeout_occurred = !result; // wait_for返回true表示未超时
});

// 不发送通知,等待超时
std::this_thread::sleep_for(std::chrono::milliseconds(150));

t1.join();
EXPECT_TRUE(timeout_occurred.load());
}

// 测试多线程通知
TEST(ConditionVariableTest, MultipleThreadsNotification) {
ThreadPool pool(4);
std::atomic counter{0};
const int num_threads = 4;

for (int i = 0; i < num_threads; ++i) { pool.enqueue([&counter]() { counter++; }); } // 等待所有任务完成 std::this_thread::sleep_for(std::chrono::milliseconds(200)); EXPECT_EQ(counter.load(), num_threads); } // 测试线程池关闭 TEST(ConditionVariableTest, ThreadPoolShutdown) { ThreadPool pool(2); std::atomic task_started{false};
std::atomic task_finished{false};

pool.enqueue([&]() {
task_started = true;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
task_finished = true;
});

// 等待任务开始
while (!task_started.load()) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}

// 关闭线程池
pool.shutdown();

// 验证任务是否完成
EXPECT_TRUE(task_started.load());
EXPECT_TRUE(task_finished.load());
}

// 性能测试
TEST(ConditionVariableTest, PerformanceBenchmark) {
ThreadPool pool(8);
const int num_tasks = 10000;
std::atomic completed{0};

auto start = std::chrono::high_resolution_clock::now();

for (int i = 0; i < num_tasks; ++i) { pool.enqueue([&completed]() { completed++; }); } // 等待所有任务完成 while (completed.load() < num_tasks) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(end – start);

std::cout << "性能测试: " << num_tasks << " 个任务耗时 " << duration.count() << " μs\n"; EXPECT_EQ(completed.load(), num_tasks); } CMake高级配置 支持不同构建类型的配置 # 在CMakeLists.txt中添加 # 设置默认构建类型 if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Release) endif() # 不同构建类型的编译选项 target_compile_options(${PROJECT_NAME} PRIVATE $<$:-O0 -g -DDEBUG>
$<$:-O3 -DNDEBUG>
$<$:-O2 -g -DNDEBUG>
)

# 链接优化选项
if(CMAKE_CXX_COMPILER_ID MATCHES “GNU|Clang”)
target_link_options(${PROJECT_NAME} PRIVATE
$<$:-flto>
)
endif()
测试配置集成
# tests/CMakeLists.txt

# 查找Google Test
find_package(GTest REQUIRED)

# 测试可执行文件
add_executable(test_condition_variable
test_condition_variable.cpp
${PROJECT_SOURCE_DIR}/src/thread_pool.cpp
${PROJECT_SOURCE_DIR}/src/condition_variable_wrapper.cpp
)

# 链接测试库
target_link_libraries(test_condition_variable
PRIVATE
GTest::GTest
GTest::Main
Threads::Threads
)

# 包含目录
target_include_directories(test_condition_variable
PRIVATE
${PROJECT_SOURCE_DIR}/include
)

# 注册测试
add_test(NAME ConditionVariableTest COMMAND test_condition_variable)
编译与运行指南
1. 创建构建目录
mkdir build
cd build
2. 配置项目
# Linux/macOS
cmake -DCMAKE_BUILD_TYPE=Release ..

# Windows (Visual Studio)
cmake -G “Visual Studio 16 2019” -A x64 ..

# Windows (MinGW)
cmake -G “MinGW Makefiles” -DCMAKE_BUILD_TYPE=Release ..
3. 编译项目
# Linux/macOS/Windows (Makefiles)
cmake –build . –config Release

# Windows (Visual Studio)
cmake –build . –config Release –target ALL_BUILD
4. 运行程序
# Linux/macOS
./ConditionVariableDemo

# Windows
Release\ConditionVariableDemo.exe
5. 运行测试
# Linux/macOS
ctest –verbose

# 或者直接运行测试可执行文件
./tests/test_condition_variable
性能优化与最佳实践
1. 避免虚假唤醒
// 正确的等待模式
void wait_for_condition(std::unique_lock& lock) {
// 使用lambda表达式检查条件,避免虚假唤醒
m_cv.wait(lock, [this]() {
return m_condition_satisfied;
});
}
2. 通知策略优化
// 批量通知优化
void notify_all_efficiently() {
// 如果只有部分线程需要唤醒,使用notify_one()
if (m_waiters_count > 0) {
m_cv.notify_one();
}

// 如果需要唤醒所有线程,使用notify_all()
if (m_all_need_wakeup) {
m_cv.notify_all();
}
}
3. 锁粒度控制
// 细粒度锁:只在必要时持有锁
void optimized_worker() {
Task task;
{
std::unique_lock lock(m_queue_mutex);
m_cv.wait(lock, [this]() {
return !m_task_queue.empty() || m_shutdown;
});

if (m_shutdown && m_task_queue.empty()) return;

task = std::move(m_task_queue.front());
m_task_queue.pop();
} // 释放锁

// 在锁外执行任务
task();
}
4. 内存对齐与原子操作
// 使用内存对齐减少缓存行冲突
struct alignas(64) CacheAlignedCounter {
std::atomic value;
// 填充到64字节,避免伪共享
char padding[64 – sizeof(std::atomic)];
};
常见问题与解决方案
1. 死锁问题
问题
:线程A等待条件,线程B在持有锁的情况下通知条件。
解决方案
:
// 错误示例
void bad_example() {
std::lock_guard lock(m_mutex);
m_condition = true;
m_cv.notify_one(); // 错误:在锁内通知
}

// 正确示例
void good_example() {
{
std::lock_guard lock(m_mutex);
m_condition = true;
} // 先释放锁
m_cv.notify_one(); // 再通知
}
2. 优先级反转
问题
:高优先级线程等待低优先级线程释放资源。
解决方案
:使用优先级继承或避免长时间持有锁。
3. 虚假唤醒
问题
:操作系统可能在没有通知的情况下唤醒线程。
解决方案
:始终使用循环或lambda检查条件。
总结
通过CMake集成条件变量,我们实现了跨平台的线程同步机制。关键要点:
跨平台兼容性
:使用C++11标准库确保代码在所有平台编译运行
高效并发
:条件变量避免忙等待,提高CPU利用率
安全性
:正确使用互斥锁和条件变量避免竞态条件
可维护性
:封装成类便于复用和测试
这种设计模式适用于:
高性能服务器
实时数据处理系统
任务调度器
生产者-消费者场景
通过本文提供的完整代码和配置,您可以快速构建自己的跨平台并发应用。
# CMake集成Condition Variable条件变量实现跨平台线程同步与高效并发控制
引言:理解条件变量在现代并发编程中的核心地位
在多线程编程中,线程同步是一个至关重要的概念。条件变量(Condition Variable)作为现代并发编程的核心工具之一,为线程间的协调与通信提供了高效的机制。本文将深入探讨如何在CMake项目中集成条件变量,实现跨平台的线程同步与高效并发控制。
条件变量的基本概念
条件变量是一种同步原语,它允许线程在某个条件不满足时挂起,直到另一个线程改变条件并通知它。条件变量通常与互斥锁(Mutex)配合使用,以避免竞态条件。
关键特性:
等待/通知机制
:线程可以等待某个条件成立,而其他线程可以通知条件已满足
避免忙等待
:相比轮询,条件变量让线程在等待时进入休眠状态,节省CPU资源
跨平台兼容性
:现代操作系统都提供了条件变量的实现
为什么选择CMake进行项目管理
CMake是一个广泛使用的构建系统生成器,它提供了:
跨平台支持
:一次编写,到处编译
模块化管理
:便于集成第三方库和自定义组件
现代C++标准支持
:轻松启用C++11/14/17/20标准
依赖管理
:简化复杂项目的构建过程
条件变量的底层实现原理
操作系统级别的实现差异
不同操作系统对条件变量的实现各有特点:
Windows平台:
使用
CONDITION_VARIABLE
结构体
API:
InitializeConditionVariable
,
SleepConditionVariableCS
,
WakeConditionVariable
Linux/Unix平台:
使用
pthread_cond_t
(POSIX线程库)
API:
pthread_cond_init
,
pthread_cond_wait
,
pthread_cond_signal
C++11标准库:
std::condition_variable
(头文件

)
提供了跨平台的统一接口
条件变量的工作流程
线程A (生产者) 线程B (消费者)
| |
|— 获取互斥锁 ————>|
|— 修改条件 ————->|
|— 发送通知 ————->|
|— 释放互斥锁 ————>|
| |
|<--- 获取互斥锁 -----------| |<--- 检查条件 -------------| |<--- 条件不满足,等待 -----| | | |<--- 收到通知 -------------| |<--- 重新检查条件 ---------| |<--- 条件满足,继续 -------| CMake项目结构设计 项目目录结构 condition_variable_project/ ├── CMakeLists.txt ├── include/ │ ├── thread_pool.h │ └── condition_variable_wrapper.h ├── src/ │ ├── main.cpp │ ├── thread_pool.cpp │ └── condition_variable_wrapper.cpp ├── tests/ │ └── test_condition_variable.cpp └── third_party/ └── (可选的第三方库) CMakeLists.txt 配置详解 # 最低CMake版本要求 cmake_minimum_required(VERSION 3.14) # 项目信息 project(ConditionVariableDemo VERSION 1.0.0 DESCRIPTION "跨平台条件变量线程同步演示" LANGUAGES CXX ) # 设置C++标准 set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) # 针对不同平台的编译器定义 if(WIN32) add_definitions(-DWIN32_LEAN_AND_MEAN) add_definitions(-DNOMINMAX) elseif(UNIX AND NOT APPLE) add_definitions(-D_GNU_SOURCE) endif() # 包含目录 include_directories( ${PROJECT_SOURCE_DIR}/include ${PROJECT_SOURCE_DIR}/src ) # 源文件集合 set(SOURCES src/main.cpp src/thread_pool.cpp src/condition_variable_wrapper.cpp ) # 创建可执行文件 add_executable(${PROJECT_NAME} ${SOURCES}) # 链接系统线程库 find_package(Threads REQUIRED) target_link_libraries(${PROJECT_NAME} PRIVATE Threads::Threads) # 编译器特定选项 if(MSVC) target_compile_options(${PROJECT_NAME} PRIVATE /W4 /WX) else() target_compile_options(${PROJECT_NAME} PRIVATE -Wall -Wextra -Wpedantic -Werror) endif() # 安装配置(可选) install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION bin LIBRARY DESTINATION lib ARCHIVE DESTINATION lib ) # 测试配置(启用测试) enable_testing() add_subdirectory(tests) 跨平台条件变量封装实现 头文件定义 (include/condition_variable_wrapper.h) #ifndef CONDITION_VARIABLE_WRAPPER_H #define CONDITION_VARIABLE_WRAPPER_H #include
#include
#include

// 跨平台条件变量封装类
class ConditionVariableWrapper {
public:
// 构造函数
ConditionVariableWrapper();

// 析构函数
~ConditionVariableWrapper();

// 禁用拷贝构造和赋值
ConditionVariableWrapper(const ConditionVariableWrapper&) = delete;
ConditionVariableWrapper& operator=(const ConditionVariableWrapper&) = delete;

// 等待条件满足(无限等待)
void wait(std::unique_lock& lock);

// 等待条件满足(带超时)
template
bool wait_for(std::unique_lock& lock,
const std::chrono::duration& timeout);

// 等待条件满足(到指定时间点)
template
bool wait_until(std::unique_lock& lock,
const std::chrono::time_point& timeout_time);

// 通知一个等待线程
void notify_one();

// 通知所有等待线程
void notify_all();

private:
std::condition_variable m_cond;
};

// 模板函数实现
template
bool ConditionVariableWrapper::wait_for(std::unique_lock& lock,
const std::chrono::duration& timeout) {
return m_cond.wait_for(lock, timeout) == std::cv_status::no_timeout;
}

template
bool ConditionVariableWrapper::wait_until(std::unique_lock& lock,
const std::chrono::time_point& timeout_time) {
return m_cond.wait_until(lock, timeout_time) == std::cv_status::no_timeout;
}

#endif // CONDITION_VARIABLE_WRAPPER_H
源文件实现 (src/condition_variable_wrapper.cpp)
#include “condition_variable_wrapper.h”

ConditionVariableWrapper::ConditionVariableWrapper() {
// std::condition_variable 在构造时自动初始化
}

ConditionVariableWrapper::~ConditionVariableWrapper() {
// std::condition_variable 在析构时自动清理
}

void ConditionVariableWrapper::wait(std::unique_lock& lock) {
if (!lock.owns_lock()) {
throw std::system_error(std::make_error_code(std::errc::operation_not_permitted),
“ConditionVariableWrapper::wait: lock must be held”);
}
m_cond.wait(lock);
}

void ConditionVariableWrapper::notify_one() {
m_cond.notify_one();
}

void ConditionVariableWrapper::notify_all() {
m_cond.notify_all();
}
实际应用案例:生产者-消费者模式
生产者-消费者头文件 (include/thread_pool.h)
#ifndef THREAD_POOL_H
#define THREAD_POOL_H

#include “condition_variable_wrapper.h”
#include
#include
#include #include
#include
#include

// 任务类型定义
using Task = std::function;

// 线程池类
class ThreadPool {
public:
// 构造函数:创建指定数量的工作线程
explicit ThreadPool(size_t num_threads);

// 析构函数:确保所有线程安全退出
~ThreadPool();

// 禁用拷贝
ThreadPool(const ThreadPool&) = delete;
ThreadPool& operator=(const ThreadPool&) = delete;

// 提交任务到线程池
void enqueue(Task task);

// 关闭线程池(等待所有任务完成)
void shutdown();

// 获取当前队列大小
size_t get_queue_size() const;

// 获取活跃线程数
size_t get_active_count() const;

private:
// 工作线程函数
void worker_thread();

// 任务队列
std::queue m_task_queue;

// 互斥锁保护任务队列
mutable std::mutex m_queue_mutex;

// 条件变量用于任务通知
ConditionVariableWrapper m_task_cv;

// 线程容器
std::vector m_workers;

// 原子标志:是否正在关闭
std::atomic m_shutdown{false};

// 原子计数器:当前正在执行的任务数
std::atomic m_active_tasks{0};
};

#endif // THREAD_POOL_H
线程池实现 (src/thread_pool.cpp)
#include “thread_pool.h”
#include
#include

ThreadPool::ThreadPool(size_t num_threads) {
if (num_threads == 0) {
throw std::invalid_argument(“ThreadPool must have at least one thread”);
}

// 创建工作线程
for (size_t i = 0; i < num_threads; ++i) { m_workers.emplace_back(&ThreadPool::worker_thread, this); } } ThreadPool::~ThreadPool() { shutdown(); } void ThreadPool::enqueue(Task task) { if (m_shutdown.load()) { throw std::runtime_error("Cannot enqueue task on shutdown ThreadPool"); } { std::lock_guard lock(m_queue_mutex);
m_task_queue.push(std::move(task));
}

// 通知一个等待的线程有新任务
m_task_cv.notify_one();
}

void ThreadPool::shutdown() {
// 双重检查避免重复关闭
bool expected = false;
if (!m_shutdown.compare_exchange_strong(expected, true)) {
return; // 已经关闭
}

// 通知所有等待的线程
{
std::lock_guard lock(m_queue_mutex);
// 空任务作为终止信号
m_task_queue.push([](){});
}
m_task_cv.notify_all();

// 等待所有线程完成
for (auto& worker : m_workers) {
if (worker.joinable()) {
worker.join();
}
}
}

size_t ThreadPool::get_queue_size() const {
std::lock_guard lock(m_queue_mutex);
return m_task_queue.size();
}

size_t ThreadPool::get_active_count() const {
return m_active_tasks.load();
}

void ThreadPool::worker_thread() {
while (true) {
Task task;

{
// 获取锁并等待任务
std::unique_lock lock(m_queue_mutex);

// 等待条件:有任务或关闭标志
m_task_cv.wait(lock, [this]() {
return !m_task_queue.empty() || m_shutdown.load();
});

// 检查是否关闭
if (m_shutdown.load() && m_task_queue.empty()) {
break;
}

// 获取任务
if (!m_task_queue.empty()) {
task = std::move(m_task_queue.front());
m_task_queue.pop();
}
}

// 执行任务(在锁外执行,避免阻塞其他线程)
if (task) {
m_active_tasks++;
try {
task();
} catch (const std::exception& e) {
std::cerr << "Task execution failed: " << e.what() << std::endl; } m_active_tasks--; } } } 主程序入口 (src/main.cpp) #include "thread_pool.h" #include
#include
#include
#include

// 模拟耗时任务
void simulate_work(int id, int duration_ms) {
std::this_thread::sleep_for(std::chrono::milliseconds(duration_ms));
std::cout << "Task " << id << " completed after " << duration_ms << "ms\n"; } // 计算密集型任务 void cpu_intensive_task(int id, int iterations) { volatile long long result = 0; for (int i = 0; i < iterations; ++i) { result += i * i; } std::cout << "CPU Task " << id << " finished with result: " << result << "\n"; } // 生产者-消费者演示 void producer_consumer_demo() { std::cout << "\n=== 生产者-消费者演示 ===\n"; ThreadPool pool(4); std::atomic counter{0};
const int num_tasks = 10;

// 生产者:提交任务
auto start = std::chrono::high_resolution_clock::now();

for (int i = 0; i < num_tasks; ++i) { pool.enqueue([i, &counter]() { simulate_work(i, 100); counter++; }); } // 等待所有任务完成 while (counter.load() < num_tasks) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(end – start);

std::cout << "所有任务完成,耗时: " << duration.count() << "ms\n"; std::cout << "最终计数器值: " << counter.load() << "\n"; } // 超时控制演示 void timeout_control_demo() { std::cout << "\n=== 超时控制演示 ===\n"; ThreadPool pool(2); std::atomic long_task_done{false};

// 提交一个长耗时任务
pool.enqueue([&long_task_done]() {
std::cout << "开始执行长耗时任务...\n"; std::this_thread::sleep_for(std::chrono::seconds(3)); long_task_done = true; std::cout << "长耗时任务完成\n"; }); // 主线程等待任务完成,但设置超时 auto start = std::chrono::high_resolution_clock::now(); const auto timeout = std::chrono::seconds(2); while (!long_task_done.load()) { auto now = std::chrono::high_resolution_clock::now(); if (now - start > timeout) {
std::cout << "任务执行超时!\n"; break; } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } if (long_task_done.load()) { std::cout << "任务在超时前完成\n"; } } // 批量任务处理演示 void batch_processing_demo() { std::cout << "\n=== 批量任务处理演示 ===\n"; ThreadPool pool(8); std::vector results(1000);
std::atomic completed{0};

auto start = std::chrono::high_resolution_clock::now();

// 提交1000个任务
for (int i = 0; i < 1000; ++i) { pool.enqueue([i, &results, &completed]() { // 模拟计算 int sum = 0; for (int j = 0; j < 100; ++j) { sum += j; } results[i] = sum; completed++; }); } // 等待完成 while (completed.load() < 1000) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(end – start);

// 验证结果
long long total = std::accumulate(results.begin(), results.end(), 0LL);
std::cout << "批量处理完成,耗时: " << duration.count() << "ms\n"; std::cout << "处理的任务数: " << completed.load() << "\n"; std::cout << "结果总和: " << total << "\n"; } int main() { std::cout << "=== CMake集成条件变量线程同步演示 ===\n"; std::cout << "平台: " << #ifdef _WIN32 "Windows" #elif __linux__ "Linux" #elif __APPLE__ "macOS" #else "Unknown" #endif << "\n"; try { producer_consumer_demo(); timeout_control_demo(); batch_processing_demo(); std::cout << "\n=== 所有演示完成 ===\n"; } catch (const std::exception& e) { std::cerr << "错误: " << e.what() << std::endl; return 1; } return 0; } 测试代码 (tests/test_condition_variable.cpp) #include
#include “thread_pool.h”
#include “condition_variable_wrapper.h”
#include
#include #include

// 测试基本功能
TEST(ConditionVariableTest, BasicNotification) {
ThreadPool pool(2);
std::atomic task_executed{false};

pool.enqueue([&task_executed]() {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
task_executed = true;
});

// 等待任务完成
auto start = std::chrono::high_resolution_clock::now();
while (!task_executed.load()) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
auto now = std::chrono::high_resolution_clock::now();
if (now – start > std::chrono::seconds(1)) {
break;
}
}

EXPECT_TRUE(task_executed.load());
}

// 测试超时机制
TEST(ConditionVariableTest, TimeoutMechanism) {
ConditionVariableWrapper cv;
std::mutex mtx;
std::atomic timeout_occurred{false};

std::thread t1([&]() {
std::unique_lock lock(mtx);
auto timeout = std::chrono::milliseconds(100);
auto result = cv.wait_for(lock, timeout);
timeout_occurred = !result; // wait_for返回true表示未超时
});

// 不发送通知,等待超时
std::this_thread::sleep_for(std::chrono::milliseconds(150));

t1.join();
EXPECT_TRUE(timeout_occurred.load());
}

// 测试多线程通知
TEST(ConditionVariableTest, MultipleThreadsNotification) {
ThreadPool pool(4);
std::atomic counter{0};
const int num_threads = 4;

for (int i = 0; i < num_threads; ++i) { pool.enqueue([&counter]() { counter++; }); } // 等待所有任务完成 std::this_thread::sleep_for(std::chrono::milliseconds(200)); EXPECT_EQ(counter.load(), num_threads); } // 测试线程池关闭 TEST(ConditionVariableTest, ThreadPoolShutdown) { ThreadPool pool(2); std::atomic task_started{false};
std::atomic task_finished{false};

pool.enqueue([&]() {
task_started = true;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
task_finished = true;
});

// 等待任务开始
while (!task_started.load()) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}

// 关闭线程池
pool.shutdown();

// 验证任务是否完成
EXPECT_TRUE(task_started.load());
EXPECT_TRUE(task_finished.load());
}

// 性能测试
TEST(ConditionVariableTest, PerformanceBenchmark) {
ThreadPool pool(8);
const int num_tasks = 10000;
std::atomic completed{0};

auto start = std::chrono::high_resolution_clock::now();

for (int i = 0; i < num_tasks; ++i) { pool.enqueue([&completed]() { completed++; }); } // 等待所有任务完成 while (completed.load() < num_tasks) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(end – start);

std::cout << "性能测试: " << num_tasks << " 个任务耗时 " << duration.count() << " μs\n"; EXPECT_EQ(completed.load(), num_tasks); } CMake高级配置 支持不同构建类型的配置 # 在CMakeLists.txt中添加 # 设置默认构建类型 if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Release) endif() # 不同构建类型的编译选项 target_compile_options(${PROJECT_NAME} PRIVATE $<$:-O0 -g -DDEBUG>
$<$:-O3 -DNDEBUG>
$<$:-O2 -g -DNDEBUG>
)

# 链接优化选项
if(CMAKE_CXX_COMPILER_ID MATCHES “GNU|Clang”)
target_link_options(${PROJECT_NAME} PRIVATE
$<$:-flto>
)
endif()
测试配置集成
# tests/CMakeLists.txt

# 查找Google Test
find_package(GTest REQUIRED)

# 测试可执行文件
add_executable(test_condition_variable
test_condition_variable.cpp
${PROJECT_SOURCE_DIR}/src/thread_pool.cpp
${PROJECT_SOURCE_DIR}/src/condition_variable_wrapper.cpp
)

# 链接测试库
target_link_libraries(test_condition_variable
PRIVATE
GTest::GTest
GTest::Main
Threads::Threads
)

# 包含目录
target_include_directories(test_condition_variable
PRIVATE
${PROJECT_SOURCE_DIR}/include
)

# 注册测试
add_test(NAME ConditionVariableTest COMMAND test_condition_variable)
编译与运行指南
1. 创建构建目录
mkdir build
cd build
2. 配置项目
# Linux/macOS
cmake -DCMAKE_BUILD_TYPE=Release ..

# Windows (Visual Studio)
cmake -G “Visual Studio 16 2019” -A x64 ..

# Windows (MinGW)
cmake -G “MinGW Makefiles” -DCMAKE_BUILD_TYPE=Release ..
3. 编译项目
# Linux/macOS/Windows (Makefiles)
cmake –build . –config Release

# Windows (Visual Studio)
cmake –build . –config Release –target ALL_BUILD
4. 运行程序
# Linux/macOS
./ConditionVariableDemo

# Windows
Release\ConditionVariableDemo.exe
5. 运行测试
# Linux/macOS
ctest –verbose

# 或者直接运行测试可执行文件
./tests/test_condition_variable
性能优化与最佳实践
1. 避免虚假唤醒
// 正确的等待模式
void wait_for_condition(std::unique_lock& lock) {
// 使用lambda表达式检查条件,避免虚假唤醒
m_cv.wait(lock, [this]() {
return m_condition_satisfied;
});
}
2. 通知策略优化
// 批量通知优化
void notify_all_efficiently() {
// 如果只有部分线程需要唤醒,使用notify_one()
if (m_waiters_count > 0) {
m_cv.notify_one();
}

// 如果需要唤醒所有线程,使用notify_all()
if (m_all_need_wakeup) {
m_cv.notify_all();
}
}
3. 锁粒度控制
// 细粒度锁:只在必要时持有锁
void optimized_worker() {
Task task;
{
std::unique_lock lock(m_queue_mutex);
m_cv.wait(lock, [this]() {
return !m_task_queue.empty() || m_shutdown;
});

if (m_shutdown && m_task_queue.empty()) return;

task = std::move(m_task_queue.front());
m_task_queue.pop();
} // 释放锁

// 在锁外执行任务
task();
}
4. 内存对齐与原子操作
// 使用内存对齐减少缓存行冲突
struct alignas(64) CacheAlignedCounter {
std::atomic value;
// 填充到64字节,避免伪共享
char padding[64 – sizeof(std::atomic)];
};
常见问题与解决方案
1. 死锁问题
问题
:线程A等待条件,线程B在持有锁的情况下通知条件。
解决方案
:
// 错误示例
void bad_example() {
std::lock_guard lock(m_mutex);
m_condition = true;
m_cv.notify_one(); // 错误:在锁内通知
}

// 正确示例
void good_example() {
{
std::lock_guard lock(m_mutex);
m_condition = true;
} // 先释放锁
m_cv.notify_one(); // 再通知
}
2. 优先级反转
问题
:高优先级线程等待低优先级线程释放资源。
解决方案
:使用优先级继承或避免长时间持有锁。
3. 虚假唤醒
问题
:操作系统可能在没有通知的情况下唤醒线程。
解决方案
:始终使用循环或lambda检查条件。
总结
通过CMake集成条件变量,我们实现了跨平台的线程同步机制。关键要点:
跨平台兼容性
:使用C++11标准库确保代码在所有平台编译运行
高效并发
:条件变量避免忙等待,提高CPU利用率
安全性
:正确使用互斥锁和条件变量避免竞态条件
可维护性
:封装成类便于复用和测试
这种设计模式适用于:
高性能服务器
实时数据处理系统
任务调度器
生产者-消费者场景
通过本文提供的完整代码和配置,您可以快速构建自己的跨平台并发应用。