c++ thread mutex

复制代码
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex

volatile int counter(0); // non-atomic counter
std::mutex mtx;           // locks access to counter

void increases_10k()
{
    for (int i=0; i<10000; ++i) {
        // 1. 使用try_lock的情况
        // if (mtx.try_lock()) {   // only increase if currently not locked:
        //     ++counter;
        //     mtx.unlock();
        // }
        // 2. 使用lock的情况
               {
                   mtx.lock();
                   ++counter;
                   mtx.unlock();
               }
    }
}

int main()
{
    std::thread threads[10];
    for (int i=0; i<10; ++i)
        threads[i] = std::thread(increases_10k);

    for (auto& th : threads) th.join();
    std::cout << " successful increases of the counter "  << counter << std::endl;

    return 0;
}

std::lock_guard 是 C++ 标准库中提供的一个模板类,用于在其构造时自动获取锁,在析构时自动释放锁。使用 std::lock_guard 的好处是,当 std::lock_guard 对象离开其作用域时,会自动调用析构函数,该析构函数会释放锁。这确保了在任何情况下(包括由于异常等原因导致的提前退出),锁都会被正确释放,从而避免了忘记手动释放锁而导致的死锁问题。

复制代码
#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx;
volatile int sharedData(0);

void threadModifySharedData(int threadId){
    
    //1.
    std::cout << "threadId:" << threadId << std::endl;

    //2.add loack
    std::lock_guard<std::mutex> lock(mtx);

    //3.
    std::cout << "thread sharedData:" << sharedData << std::endl;

    //4.modif sharedData
    sharedData++;

}


int main(void){

    const size_t numThread = 10;
    std::thread threads[numThread];

    for(size_t i = 0; i < numThread; i++)
        threads[i] = std::thread(threadModifySharedData, i+1);

    for(size_t i = 0; i < numThread; i++)
        threads[i].join();

    std::cout << "main sharedData:" << sharedData << std::endl;

    return 0;
}

std::recursive_mutex:递归互斥锁,允许同一个线程多次锁定

复制代码
#include <iostream>
#include <mutex>
#include <thread>

struct Complx{
    int i;
    std::recursive_mutex mtx;

    Complx(int ii= 10):i(ii){
        std::cout << "Complx(int ii):i(ii)" << std::endl;
    }

    ~Complx(void){
        std::cout << "~Complx(void)" << std::endl;
    }

    void mul(int x){
        std::lock_guard<std::recursive_mutex> lock(mtx);
        i *= x;
    }

    void div(int x){
        std::lock_guard<std::recursive_mutex> lock(mtx);
        i += x;
    }

    void both(int x, int y){
        std::lock_guard<std::recursive_mutex> lock(mtx);
        mul(x);
        div(y);
    }
};

int main(void){
    Complx cpx(200);

    cpx.both(100,200);

    std::cout << "i:" << cpx.i << std::endl;

    return 0;
}
相关推荐
Lhan.zzZ1 小时前
笔记_2026.4.28_004
c++·ide·笔记·qt
MATLAB代码顾问2 小时前
5大智能算法优化标准测试函数对比(Python实现)
开发语言·python
wuminyu3 小时前
专家视角看Java字节码加载与存储指令机制
java·linux·c语言·jvm·c++
万粉变现经纪人3 小时前
如何解决 pip install llama-cpp-python 报错 未安装 CMake/Ninja 或 CPU 不支持 AVX 问题
开发语言·python·开源·aigc·pip·ai写作·llama
清风明月一壶酒3 小时前
OpenClaw自动处理Word文档全流程
开发语言·c#·word
其实防守也摸鱼3 小时前
CTF密码学综合教学指南--第五章
开发语言·网络·笔记·python·安全·网络安全·密码学
木喃的井盖3 小时前
无锁队列细节
c++·工程
王老师青少年编程4 小时前
csp信奥赛C++高频考点专项训练之字符串 --【字符串基础】:输出亲朋字符串
c++·字符串·csp·高频考点·信奥赛·专项训练·输出亲朋字符串
MediaTea4 小时前
AI 术语通俗词典:C4.5 算法
人工智能·算法
Navigator_Z4 小时前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode