C11:mutex和lock_guard的使用.

在C++11中,引入了有关线程的一系列库.且都在std命名空间内.下面演示一个使用线程的例子.非常的简单.引入了thread和mutex头文件.

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;

int g_i = 0;
mutex g_mutex;
void c()
{
    for (int i = 0; i < 20; ++i)
    {
        g_mutex.lock();
        cout << std::this_thread::get_id() << "  " << g_i++ << endl;
        g_mutex.unlock();
    }
}

int main()
{
    thread t1(c);
    thread t2(c);

    if (t1.joinable())
        t1.join();
    if (t2.joinable())
        t2.join();

    system("pause");
    return 0;
}
//打印结果.
932  0
10340  1
932  2
10340  3
932  4

我们使用mutex互斥锁,来保证线程的安全性.但是这样是很麻烦的.我们需要手动的对锁进行操作.如果出现多个分支的情况,则需要多次书写unlock操作.

所以引入了lock_guard对象.它是管理锁的模板类.

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;

int g_i = 0;
mutex g_mutex;
void c()
{
    for (int i = 0; i < 20; ++i)
    {
        lock_guard<mutex> lock(g_mutex);
        cout << std::this_thread::get_id() << "  " << g_i++ << endl;
    }
}

int main()
{
    thread t1(c);
    thread t2(c);

    if (t1.joinable())
        t1.join();
    if (t2.joinable())
        t2.join();

    system("pause");
    return 0;
}

//它被用作临时变量来使用,用g_mutex锁进行初始化,初始化的时候就是锁的lock操作的时候,那么什么时候unlock呢?就是在超出它的作用域之后析构时unlock.

//初始化时lock.
explicit lock_guard(_Mutex& _Mtx)
        : _MyMutex(_Mtx)
        {   // construct and lock
        _MyMutex.lock();
        }

    lock_guard(_Mutex& _Mtx, adopt_lock_t)
        : _MyMutex(_Mtx)
        {   // construct but don't lock
        }
//析构时unlock.
    ~lock_guard() _NOEXCEPT
        {   // unlock
        _MyMutex.unlock();
        }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值