网上关于信号量和锁的区别,写的比较官方晦涩难懂,对于这个知识点吸收难,通过示例,我们看到信号量,可以控制同一时刻的线程数量,就算同时开启很多线程,依然可以的达到线程数可控
#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); // 初始化信号量,最大值为2
std::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;
}
经过多轮测试,线程安全还是得依赖锁