網上關于信號量和鎖的區別,寫的比較官方晦澀難懂,對于這個知識點吸收難,通過示例,我們看到信號量,可以控制同一時刻的線程數量,就算同時開啟很多線程,依然可以的達到線程數可控
#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;
}
經過多輪測試,線程安全還是得依賴鎖