当前位置: 首页 > java >正文

Windows下的临界写法

#include <windows.h>

class CriticalSection {
public:
    CriticalSection() {
        InitializeCriticalSection(&cs_);
    }

    ~CriticalSection() {
        DeleteCriticalSection(&cs_);
    }

    // 辅助 Guard 类实现自动加锁/解锁
    class Guard {
    public:
        explicit Guard(CriticalSection& cs) : cs_(cs) {
            EnterCriticalSection(&cs_.cs_);
        }

        ~Guard() {
            LeaveCriticalSection(&cs_.cs_);
        }

        // 禁用拷贝与移动
        Guard(const Guard&) = delete;
        Guard& operator=(const Guard&) = delete;

    private:
        CriticalSection& cs_;
    };

private:
    CRITICAL_SECTION cs_;

    // 禁用拷贝与移动
    CriticalSection(const CriticalSection&) = delete;
    CriticalSection& operator=(const CriticalSection&) = delete;
};
怎么用呢?

// 全局共享资源与临界区
CriticalSection g_cs;
int g_sharedData = 0;

void ThreadFunction() {
    for (int i = 0; i < 1000; ++i) {
        CriticalSection::Guard lock(g_cs); // 自动加锁
        ++g_sharedData;                   // 临界区操作
    }                                     // 自动解锁
}

int main() {
    HANDLE threads[2];
    threads[0] = CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)ThreadFunction, nullptr, 0, nullptr);
    threads[1] = CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)ThreadFunction, nullptr, 0, nullptr);

    WaitForMultipleObjects(2, threads, TRUE, INFINITE);
    CloseHandle(threads[0]);
    CloseHandle(threads[1]);

    std::cout << "Final value: " << g_sharedData << std::endl; // 正确输出 2000
    return 0;
}
 

http://www.xdnf.cn/news/5223.html

相关文章:

  • 回文数(9)
  • 气象大模型光伏功率预测中的应用:从短期,超短期,中长期的实现与开源代码详解
  • C++GO语言微服务之图片、短信验证码生成及存储
  • 【沉浸式求职学习day35】【Tomcat安装、配置】【Http简述】
  • Linux指令入门:DevOps与SRE视角
  • SDC命令详解:使用all_outputs命令进行查询
  • 轻松制作高质量视频,实时生成神器LTX-Video重磅登场!
  • 睿思量化小程序
  • LeetCode 88. 合并两个有序数组 | Python 最简写法 + 实战注释
  • Java面向对象
  • bcm5482 phy 场景总结
  • 技嘉主板BIOS升级
  • 树 Part 4
  • D. Apple Tree Traversing 【Codeforces Round 1023 (Div. 2)】
  • NX949NX952美光科技闪存NX961NX964
  • 短剧 CPS 分销系统开发搭建,开启流量变现新征程
  • 数字签名与证书
  • 北斗终端设备应用
  • 【含文档+源码】基于SpringBoot的新能源充电桩管理系统的设计与实现
  • ODA服务器计算节点本地硬盘状态异常的处理
  • 【金仓数据库征文】国产数据库KingbaseES安装与使用详解
  • 202535| Kafka架构与重要概念+幂等性+事务
  • [架构之美]Spring Boot多环境5种方案实现Dev/Test/Prod环境隔离
  • kafka的安装及简单使用
  • 【并发编程】基于 Redis 手写分布式锁
  • 【源码+文档+调试讲解】高校创新创业课程124
  • Metasploit 4.22.7:企业级渗透测试新突破
  • 深入了解 ArkTS:HarmonyOS 开发的关键语言与应用实践
  • 装机容量与额定容量区别解析
  • 记录 ubuntu 安装中文语言出现 software database is broken