C++信号量实战:如何用Semaphore解决多线程打印ABC问题(附完整代码)

张开发
2026/4/7 3:57:22 15 分钟阅读

分享文章

C++信号量实战:如何用Semaphore解决多线程打印ABC问题(附完整代码)
C信号量实战如何用Semaphore解决多线程打印ABC问题附完整代码多线程编程中同步机制的选择往往决定了程序的性能和可靠性。信号量Semaphore作为一种经典的同步原语在解决特定类型的问题时展现出独特的优势。今天我们就以经典的ABC顺序打印问题为例深入探讨C20标准引入的semaphore头文件的实际应用。1. 理解信号量的核心机制信号量本质上是一个计数器它通过两个原子操作acquire和release来控制对共享资源的访问。与互斥锁不同信号量允许多个线程同时访问资源只是通过计数器限制最大并发数。在C20中标准库提供了两种信号量类型std::counting_semaphore计数信号量允许非负资源计数std::binary_semaphore二元信号量本质上是计数信号量的特例最大值为1信号量的关键操作// 构造计数信号量初始值为desired constexpr explicit counting_semaphore(std::ptrdiff_t desired); // 获取资源计数器减1若计数器为0则阻塞 void acquire(); // 释放资源计数器加1唤醒等待线程 void release(std::ptrdiff_t update 1);2. ABC打印问题的信号量解法多线程顺序打印ABC是一个经典的同步问题要求三个线程严格按照A→B→C的顺序循环输出。信号量的特性使其成为解决这类问题的理想选择。2.1 解决方案设计思路我们需要三个信号量分别控制A、B、C线程的执行顺序线程A执行后释放B的信号量线程B执行后释放C的信号量线程C执行后释放A的信号量这种设计形成了一个闭环的接力棒传递机制确保执行顺序的严格性。2.2 完整实现代码#include iostream #include thread #include semaphore using namespace std; // 初始化三个信号量 counting_semaphore semA(1); // A线程先执行 counting_semaphore semB(0); // B线程等待 counting_semaphore semC(0); // C线程等待 void printA(int count) { for (int i 0; i count; i) { semA.acquire(); // 获取A信号量 cout A flush; semB.release(); // 释放B信号量 } } void printB(int count) { for (int i 0; i count; i) { semB.acquire(); // 获取B信号量 cout B flush; semC.release(); // 释放C信号量 } } void printC(int count) { for (int i 0; i count; i) { semC.acquire(); // 获取C信号量 cout C flush; semA.release(); // 释放A信号量 } } int main() { const int printCount 10; // 每个字母打印次数 thread tA(printA, printCount); thread tB(printB, printCount); thread tC(printC, printCount); tA.join(); tB.join(); tC.join(); cout endl; return 0; }3. 关键实现细节解析3.1 信号量初始值的设定初始值的设定是信号量应用的关键semA初始为1允许A线程立即执行semB和semC初始为0阻塞B、C线程直到前驱线程释放信号量3.2 执行流程分析A线程获取semA计数器从1→0打印AA线程释放semB计数器从0→1唤醒B线程B线程获取semB1→0打印BB线程释放semC0→1唤醒C线程C线程获取semC1→0打印CC线程释放semA0→1唤醒A线程循环上述步骤直到完成指定次数3.3 为什么使用信号量而非互斥锁与互斥锁相比信号量方案有几个优势明确的执行顺序控制每个线程只关心自己的前驱线程避免忙等待线程在无权限时自动阻塞不消耗CPU可扩展性强同样的模式可以扩展到更多线程的顺序控制4. 进阶应用与性能考量4.1 处理异常情况在实际应用中我们需要考虑线程异常退出的情况。一个健壮的实现应该包含异常处理void printA(int count) { try { for (int i 0; i count; i) { semA.acquire(); cout A flush; semB.release(); } } catch (...) { // 异常时释放信号量避免死锁 semB.release(); throw; } }4.2 性能优化技巧在多核处理器上可以考虑以下优化使用try_acquire_for避免长时间阻塞if (!semA.try_acquire_for(100ms)) { // 超时处理逻辑 }调整线程优先级确保关键线程优先执行使用线程池减少线程创建销毁开销4.3 扩展到N个线程的顺序控制同样的模式可以推广到任意数量线程的顺序控制。例如控制5个线程按顺序打印A-E// 初始化信号量数组 arraycounting_semaphore, 5 sems; sems[0].release(1); // 第一个信号量可用 // 线程函数模板 auto printer [](int index, char ch) { for (int i 0; i count; i) { sems[index].acquire(); cout ch flush; sems[(index 1) % 5].release(); } };5. 信号量与其它同步机制的对比5.1 信号量 vs 互斥锁特性信号量互斥锁所有权无关联与线程关联计数可大于1二元状态释放可由不同线程释放必须由获取线程释放性能轻量级相对较重5.2 信号量 vs 条件变量虽然条件变量也能实现类似功能但信号量方案有几个明显优势更简洁不需要额外的谓词变量和锁更高效减少了一次锁操作的开销更直观计数机制直接反映了可用资源量提示在C中条件变量通常需要与互斥锁配合使用而信号量是自包含的同步原语。6. 实际项目中的应用场景信号量特别适合以下场景生产者-消费者问题限制缓冲区大小读写锁实现控制读写线程比例线程池任务调度限制最大并发任务数资源池管理如数据库连接池以线程池任务调度为例class ThreadPool { counting_semaphore taskSemaphore{0}; queuefunctionvoid() tasks; mutex queueMutex; vectorthread workers; public: ThreadPool(size_t threads) { for (size_t i 0; i threads; i) { workers.emplace_back([this] { while (true) { taskSemaphore.acquire(); functionvoid() task; { lock_guardmutex lock(queueMutex); if (tasks.empty()) continue; task move(tasks.front()); tasks.pop(); } task(); } }); } } void enqueue(functionvoid() task) { { lock_guardmutex lock(queueMutex); tasks.emplace(move(task)); } taskSemaphore.release(); } };7. 调试与性能分析技巧调试多线程程序时信号量的状态监控至关重要。可以添加调试输出class DebugSemaphore { counting_semaphore sem; string name; public: DebugSemaphore(ptrdiff_t desired, string name) : sem(desired), name(move(name)) {} void acquire() { cout name acquiring (before: sem.max() - sem.try_acquire_until(chrono::system_clock::now()) ) endl; sem.acquire(); cout name acquired endl; } void release(ptrdiff_t update 1) { sem.release(update); cout name released (now: sem.max() - sem.try_acquire_until(chrono::system_clock::now()) ) endl; if (update 0) sem.release(update); // 补偿try_acquire_until的消耗 } };对于性能分析可以使用chrono测量关键区段执行时间auto start chrono::high_resolution_clock::now(); // 关键代码段 auto end chrono::high_resolution_clock::now(); cout Duration: chrono::duration_castchrono::microseconds(end - start).count() μs endl;8. 常见问题与解决方案8.1 死锁问题症状程序挂起所有线程都在等待原因信号量释放次数不足异常导致信号量未释放解决方案使用RAII包装信号量操作class SemaphoreGuard { counting_semaphore sem; public: explicit SemaphoreGuard(counting_semaphore s) : sem(s) { sem.acquire(); } ~SemaphoreGuard() { sem.release(); } };8.2 顺序错乱症状输出顺序不符合预期原因信号量初始值设置错误释放了错误的信号量解决方案仔细检查信号量初始值为每个信号量添加有意义的名称添加调试输出跟踪信号量状态8.3 性能瓶颈症状多线程性能不如单线程原因关键区段过大信号量竞争激烈解决方案缩小关键区段范围考虑使用无锁数据结构评估是否真的需要严格顺序9. 现代C中的最佳实践9.1 使用RAII管理信号量class ScopedSemaphore { counting_semaphore sem; bool acquired; public: explicit ScopedSemaphore(counting_semaphore s) : sem(s), acquired(false) { sem.acquire(); acquired true; } ~ScopedSemaphore() { if (acquired) { sem.release(); } } // 防止拷贝 ScopedSemaphore(const ScopedSemaphore) delete; ScopedSemaphore operator(const ScopedSemaphore) delete; };9.2 结合Lambda表达式auto synchronized [sem](auto func) { sem.acquire(); try { func(); sem.release(); } catch (...) { sem.release(); throw; } }; synchronized([]{ cout This is synchronized output endl; });9.3 使用C20特性简化代码// 使用jthread自动管理线程生命周期 std::jthread tA(printA, printCount); std::jthread tB(printB, printCount); std::jthread tC(printC, printCount); // 使用stop_token处理优雅退出 void printA(stop_token st, int count) { for (int i 0; i count !st.stop_requested(); i) { semA.acquire(); cout A flush; semB.release(); } }

更多文章