C++ 多线程和互斥锁(一文搞定)

这里写目录标题

1. 实验

  1. 简介:我们启动并行启动两个线程,但设置一个全局互斥锁,在两个线程中等待并占用互斥锁,然后输出日志。

  2. 代码

    #include <iostream>
    #include <thread>           /* C++ 多线程库 */
    #include <mutex>            /* C++ 互斥锁 */
    
    
    
    /* 定义一个全局锁子 */
    std::mutex mt;
    
    
    /* 定义线程1 */
    void thread_1()
    {
        /* 等待其他程序将这个锁解开,并以当前程序名义上锁, 在程序结束时自动解锁*/
        std::lock_guard<std::mutex> guard(mt);
        
        for(int i=10; i >0 ; i--){
            std::cout << "thread 1 , i = " << i << std::endl;
            std::this_thread::sleep_for(std::chrono::microseconds(100));
        }
        
        std::cout << "thread_1  end." << std::endl; 
    }
    
    /* 定义线程2 */
    void thread_2()
    {
        /* 等待其他程序将这个锁解开,并以当前程序名义上锁, 在程序结束时自动解锁*/
        std::lock_guard<std::mutex> guard(mt);
    
        for(int i=10; i >0 ; i--){
            std::cout << "thread 2 , i = " << i << std::endl;
            std::this_thread::sleep_for(std::chrono::microseconds(100));
        }  
    
        std::cout << "thread_2  end." << std::endl; 
    
    }
    
    int main(int argc, char const *argv[])
    {
        std::cout << "-------------------------------- "  << std::endl;
    
        /* 启动两个线程并行执行函数(注意这里已经开始运行了两个函数) */
        std::thread t1(thread_1);
        std::thread t2(thread_2);
    
    
        /* 阻塞等待线程的结束标志 */
        t1.join();
        t2.join();
        
        
        std::this_thread::sleep_for(std::chrono::seconds(20));
        std::cout << "-------------------------------- "  << std::endl;
    
        return 0;
    }
    
    
  3. 实验结果,上述代码执行结果

    在这里插入图片描述

  4. 如果注释等待并占用互斥锁,实验结果如下

    在这里插入图片描述

2. 手动锁与手动释放

  1. cpp一些用法
    /* 互斥所的声明 */
    std::mutex mt;
    
    /* 手动上锁,上锁不成功会堵塞等待其他程序释放 */
    std::unique_lock<std::mutex> lock(mt);
    
    /* 当前程序上锁后,释放锁的权限 */
    lock.unlock();
    
  • 12
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小灰灰的大灰灰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值