c++11新特性跨平台线程锁之lock_guard和unique_lock

在 C++1x 之后,多线程编程可以直接使用标准库里的函数,如#include <thread>#include <mutex>不必根据平台的不同使用 posix_thread 之类的库了,即实现了跨平台的编程。

本次是将日常用到的创建多线程方法以及锁的简单实现进行总结:

#include <iostream>
#include <thread>
#include <stdlib.h>
#include <windows.h>
#include <mutex>

using namespace std;

const int nt = 8;
mutex mtx; // 互斥锁

void func1()
{   
    /*
        利用lock_guard加锁;
        定义lock_guard的时候调用构造函数加锁,大括号解锁的时候调用析构函数解锁;
    */

    lock_guard<mutex> lock(mtx);
    for (int i = 0; i < 3; i++) {
        cout << "thread id is " << this_thread::get_id() << ", " << "i is " << i << endl;
        Sleep(1000);
    }
}

void func2()
{
    /*
        利用unique_lock加锁;
        可以利用 unique.unlock() 随时解锁,减小锁的粒度;
        缺点是内部会维护一个锁的状态,效率比lock_guard低一点;

        注:析构的时候会判断当前锁的状态来决定是否解锁,如果当前状态已经是解锁状态了,
           那么就不会再次解锁,而如果当前状态是加锁状态,就会自动调用unique.unlock()来解锁。
    */ 
    unique_lock<mutex> unique(mtx);
    for (int i = 0; i < 3; i++) {
        cout << "thread id is " << this_thread::get_id() << ", " << "i is " << i << endl;
        Sleep(1000);
    }
    // unique.unlock();
}

void func3()
{
    /*
        利用mtx.lock()加锁;
        利用 mtx.unlock() 随时解锁,减小锁的粒度;
        通用方法;
    */
    mtx.lock();
    for (int i = 0; i < 3; i++) {
        cout << "thread id is " << this_thread::get_id() << ", " << "i is " << i << endl;
        Sleep(1000);
    }
    mtx.unlock();
}

int main()
{
    thread t[nt];

    // 创建线程
    for (int i = 0; i < nt; i++) {
        t[i] = thread(func3);
        thread::id pid = t[i].get_id();
        //cout << "thread id is : " << pid << endl;
    }

    // 等待线程完成
    for (int i = 0; i < nt; i++) {
        t[i].join();
    }

    return 0;
}

参考:C++11多线程编程(三)——lock_guard和unique_lock - 知乎 (zhihu.com)https://zhuanlan.zhihu.com/p/340348726

( C++ thread用法总结(整理)_顺其自然~的博客-CSDN博客https://fuhanghang.blog.csdn.net/article/details/114818215?spm=1001.2101.3001.6650.7&utm_medium=distribute.pc_relevant.none-task-blog-2~default~BlogCommendFromBaidu~Rate-7-114818215-blog-118325905.235%5Ev38%5Epc_relevant_anti_t3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~BlogCommendFromBaidu~Rate-7-114818215-blog-118325905.235%5Ev38%5Epc_relevant_anti_t3&utm_relevant_index=12

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值