当前位置: 首页> 房产> 家装 > C++ 信号量和锁的区别

C++ 信号量和锁的区别

时间:2025/7/13 12:31:49来源:https://blog.csdn.net/m0_56306892/article/details/140268193 浏览次数:1次

网上关于信号量和锁的区别,写的比较官方晦涩难懂,对于这个知识点吸收难,通过示例,我们看到信号量,可以控制同一时刻的线程数量,就算同时开启很多线程,依然可以的达到线程数可控

#include <iostream>
#include <thread>
#include <vector>
#include <semaphore.h>sem_t sem;
int shared_resource = 0;void thread_func(int id) {sem_wait(&sem); // P操作shared_resource++;std::cout << "Thread " << id << " incremented shared_resource to " << shared_resource << std::endl;std::this_thread::sleep_for(std::chrono::seconds(1)); // 模拟工作sem_post(&sem); // V操作
}int main() {const int num_threads = 20000;sem_init(&sem, 0, 2); // 初始化信号量,最大值为2std::vector<std::thread> threads;for (int i = 0; i < num_threads; ++i) {threads.push_back(std::thread(thread_func, i));}for (auto& t : threads) {t.join();}sem_destroy(&sem);return 0;
}

经过多轮测试,线程安全还是得依赖锁
在这里插入图片描述

关键字:C++ 信号量和锁的区别

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: