信号量Semaphore

news/2024/10/18 23:24:40/

什么是信号量?

C++中的信号量(Semaphore)是一种同步对象,用于控制对共享资源的访问,以防止多个线程或进程同时访问同一资源,从而避免数据不一致的问题。信号量通过维护一个计数值来实现这一功能,该计数值表示可以同时访问共享资源的线程或进程的数量。当一个线程或进程想要访问共享资源时,它会尝试减少信号量的计数值;如果计数值大于零,线程或进程可以继续执行,否则它必须等待直到信号量的计数值变为正数。当线程或进程完成对共享资源的访问后,它会释放信号量,即增加计数值,从而可能允许其他正在等待的线程或进程继续执行。

信号量可以干什么?

  1. 互斥
  2. 限制并发访问
  3. 线程同步
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <condition_variable>class Semaphore {
public:Semaphore(int count = 1) : count_(count) {}void notify() {std::unique_lock<std::mutex> lock(mutex_);++count_;condition_.notify_one();}void wait() {std::unique_lock<std::mutex> lock(mutex_);while (count_ <= 0) {condition_.wait(lock);}--count_;}private:std::mutex mutex_;std::condition_variable condition_;int count_;
};// 共享资源
int sharedResource = 0;void workerFunction(Semaphore& semaphore) {for (int i = 0; i < 1000; ++i) {semaphore.wait(); // 加锁++sharedResource;semaphore.notify(); // 解锁}
}//实现互斥int main() {Semaphore semaphore(1);std::vector<std::thread> threads;// 创建 10 个工作线程for (int i = 0; i < 10; ++i) {threads.push_back(std::thread(workerFunction, std::ref(semaphore)));}// 等待所有线程完成for (auto& thread : threads) {thread.join();}std::cout << "Shared resource value: " << sharedResource << std::endl;return 0;
}
#include <iostream>
#include <thread>
#include <vector>
#include <chrono>
#include <mutex>
#include <condition_variable>class Semaphore {
public:Semaphore(int count = 1) : count_(count) {}void notify() {std::unique_lock<std::mutex> lock(mutex_);++count_;condition_.notify_one();}void wait() {std::unique_lock<std::mutex> lock(mutex_);while (count_ <= 0) {condition_.wait(lock);}--count_;}private:std::mutex mutex_;std::condition_variable condition_;int count_;
};void workerFunction(int threadId, Semaphore& semaphore) {semaphore.wait(); // 获取访问权限std::cout << "Thread " << threadId << " is accessing the shared resource." << std::endl;// 模拟访问共享资源std::this_thread::sleep_for(std::chrono::seconds(1));std::cout << "Thread " << threadId << " has finished accessing the shared resource." << std::endl;semaphore.notify(); // 释放访问权限
}//限制并发访问int main() {Semaphore semaphore(3); // 允许最多3个线程同时访问std::vector<std::thread> threads;// 创建10个工作线程for (int i = 0; i < 10; ++i) {threads.push_back(std::thread(workerFunction, i, std::ref(semaphore)));}// 等待所有线程完成for (auto& thread : threads) {thread.join();}return 0;
}
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <condition_variable>class Semaphore {
public:Semaphore(int count = 1) : count_(count) {}void notify() {std::unique_lock<std::mutex> lock(mutex_);++count_;condition_.notify_one();}void wait() {std::unique_lock<std::mutex> lock(mutex_);while (count_ <= 0) {condition_.wait(lock);}--count_;}private:std::mutex mutex_;std::condition_variable condition_;int count_;
};void task1(Semaphore& semaphore1, Semaphore& semaphore2) {std::cout << "Task 1 is executing." << std::endl;// 模拟任务执行std::this_thread::sleep_for(std::chrono::seconds(1));std::cout << "Task 1 is completed." << std::endl;// 通知任务2可以开始执行semaphore1.notify();// 等待任务2完成// semaphore2.wait();
}void task2(Semaphore& semaphore1, Semaphore& semaphore2) {// 等待任务1完成semaphore1.wait();std::cout << "Task 2 is executing." << std::endl;// 模拟任务执行std::this_thread::sleep_for(std::chrono::seconds(1));std::cout << "Task 2 is completed." << std::endl;// 通知任务3可以开始执行semaphore2.notify();
}void task3(Semaphore& semaphore2) {// 等待任务2完成semaphore2.wait();std::cout << "Task 3 is executing." << std::endl;// 模拟任务执行std::this_thread::sleep_for(std::chrono::seconds(1));std::cout << "Task 3 is completed." << std::endl;
}//线程同步int main() {Semaphore semaphore1(0), semaphore2(0);std::thread t1(task1, std::ref(semaphore1), std::ref(semaphore2));std::thread t2(task2, std::ref(semaphore1), std::ref(semaphore2));std::thread t3(task3, std::ref(semaphore2));t1.join();t2.join();t3.join();return 0;
}

信号量怎么实现?

C++11

使用互斥锁和条件变量模拟信号量。

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>class Semaphore {
public:Semaphore(int count) : _count(count) {}void acquire() {std::unique_lock<std::mutex> lock(_mutex);while (_count == 0) {_cv.wait(lock);}--_count;}void release() {std::lock_guard<std::mutex> lock(_mutex);++_count;_cv.notify_one();}private:int _count;std::mutex _mutex;std::condition_variable _cv;
};Semaphore taskSemaphore(4); // 最大并发数为4void processTask(int taskID) {taskSemaphore.acquire();std::cout << "Task " << taskID << " started." << std::endl;std::this_thread::sleep_for(std::chrono::seconds(10));std::cout << "Task " << taskID << " finished." << std::endl;taskSemaphore.release();
}int main() {std::vector<std::thread> threads;const int numTasks = 10;for (int i = 1; i <= numTasks; ++i) {threads.emplace_back(processTask, i);}for (auto& thread : threads) {thread.join();}return 0;
}

C++20

使用std::counting_semaphore

#include <iostream>
#include <thread>
#include <semaphore>
#include <vector>// 假设我们有一个最大并发数为4的任务队列
std::counting_semaphore<4> taskSemaphore(4);void processTask(int taskID) {// 请求一个任务许可taskSemaphore.acquire();std::cout << "Task " << taskID << " started." << std::endl;// 这里模拟任务处理时间std::this_thread::sleep_for(std::chrono::milliseconds(10000));std::cout << "Task " << taskID << " finished." << std::endl;// 任务处理完释放许可taskSemaphore.release();
}int main() {std::vector<std::thread> threads;const int numTasks = 10;for (int i = 1; i <= numTasks; ++i) {threads.emplace_back(processTask, i);}for (auto& thread : threads) {thread.join();}return 0;
}

经典生产者消费者问题

#include <iostream>
#include <thread>
#include <vector>
#include <queue>
#include <chrono>
#include <mutex>
#include <condition_variable>class Semaphore {
public:Semaphore(int count = 1) : count_(count) {}void notify() {std::unique_lock<std::mutex> lock(mutex_);++count_;condition_.notify_one();}void wait() {std::unique_lock<std::mutex> lock(mutex_);while (count_ <= 0) {condition_.wait(lock);}--count_;}private:std::mutex mutex_;std::condition_variable condition_;int count_;
};const int BUFFER_SIZE = 10;
std::queue<int> buffer;
std::mutex mutex_; // 互斥锁,用于保护共享数据
Semaphore empty(BUFFER_SIZE), full(0);void producer(int producerId) {for (int i = 0; i < 100; ++i) {empty.wait(); // 等待缓冲区有空位std::unique_lock<std::mutex> lock(mutex_);buffer.push(i);std::cout << "Producer " << producerId << " produced: " << i << std::endl;lock.unlock();full.notify(); // 通知消费者有新数据}
}void consumer(int consumerId) {for (int i = 0; i < 100; ++i) {full.wait(); // 等待缓冲区有数据std::unique_lock<std::mutex> lock(mutex_);int data = buffer.front();buffer.pop();std::cout << "Consumer " << consumerId << " consumed: " << data << std::endl;lock.unlock();empty.notify(); // 通知生产者有空位}
}int main() {std::vector<std::thread> producers, consumers;// 创建3个生产者线程for (int i = 0; i < 3; ++i) {producers.push_back(std::thread(producer, i));}// 创建3个消费者线程for (int i = 0; i < 3; ++i) {consumers.push_back(std::thread(consumer, i));}// 等待所有生产者线程完成for (auto& producer : producers) {producer.join();}// 等待所有消费者线程完成for (auto& consumer : consumers) {consumer.join();}return 0;
}


http://www.ppmy.cn/news/1438679.html

相关文章

Linux:强制用户访问加密(强制让用户使用https访问)

Linux&#xff1a;强制用户访问加密&#xff08;强制让用户使用https访问&#xff09; [rootserver100 ~]# vim /etc/nginx/conf.d/vhosts.conf# 修改扩展配置文件如下#下面是对访问http进行重写&#xff0c;自动导向到https server{listen 80;server_name login.timinglee.o…

了解时间复杂度和空间复杂度

在学习数据结构前&#xff0c;我们需要了解时间复杂度和空间复杂度的概念&#xff0c;这能够帮助我们了解数据结构。 算法效率分为时间效率和空间效率 时间复杂度 一个算法的复杂度与其执行的次数成正比。算法中执行基础操作的次数&#xff0c;为算法的时间复杂度。 我们采…

2023年度北京市职称评审专业、机构及联系电话

2023年度北京市职称评审专业、机构及联系电话 序号 系列 评委会及级别 评审专业 评审服务机构 联系 电话 职称申报与评审系统使用和技术支持 12333 1 自然科学研究 高、中、初级&#xff08;含正高级&#xff09; 生物医药研究、计算机与信息技术研究、环境科学与工…

Excel如何计算时间差

HOUR(B1-A1)&"小时 "&MINUTE(B1-A1)&"分钟 "&SECOND(B1-A1)&"秒"

【SAP ME 12】SAP NWDS(eclipse)下载、安装,配置

1、下载 1.1、描述 1.2、下载 2、安装 3、配置 3.1、域名映射

基于DEAP数据集的四种机器学习方法的情绪分类

在机器学习领域&#xff0c;KNN&#xff08;K-Nearest Neighbors&#xff09;、SVM&#xff08;Support Vector Machine&#xff09;、决策树&#xff08;Decision Tree&#xff09;和随机森林&#xff08;Random Forest&#xff09;是常见且广泛应用的算法。 介绍 1. KNN&am…

个人学习-前端相关(1):ECMAScript 6-变量、模板字符串、解构表达式

前言 由于最近公司有接到一些小程序或者app相关的内容&#xff0c;可能考虑要做一些样例供参考。虽然在20年短暂学习和使用过vue2&#xff0c;但由于时间久远且技术发展太快&#xff0c;需要对一些旧知识进行巩固&#xff0c;新的内容进行学习。 ECMAScript 6简介 ECMAScrip…

MySQL InnoDB事务隔离级别与锁机制深入解析

引言 在当今的数据库系统中&#xff0c;事务管理是确保数据一致性和完整性的关键。事务是数据库操作的基本单元&#xff0c;它将一系列的数据库操作组合成一个逻辑工作单元&#xff0c;要么全部成功执行&#xff0c;要么全部失败回滚&#xff0c;这就是所谓的ACID属性&#xf…