22.线程自解锁

代码结构比较复杂的情况下,手动加锁,解锁,可能会有所遗漏。

这种情况下,推荐使用自解锁(自解锁在构造的时候lock,在析构的时候unlock)(对象在超出作用域时会执行析构)

自解锁,手动锁优缺点:自解锁每次都会构造,析构。在执行效率上没有手动锁效率高。

演示代码:

示例一:手动加锁,解锁(要在每个代码分支的地方保证解锁)

#include <iostream>
#include <thread>
#include <mutex>

using namespace std;

mutex m_lock;

void workFun(int index)
{

    for (int i = 0; i < 1000; i++)
    {

        m_lock.lock();
        if (i > 500)
        {
            m_lock.unlock();
            return;
        }
        
        cout << index << " child thread " << i << endl;
        m_lock.unlock();

    }

}//抢占式

int main()
{
    thread t[3];
    for (int n = 0; n<3; n++)
    {
        t[n] = thread(workFun, n);
    }

    for (int n = 0; n<3; n++)
    {
        t[n].join();
    }

    for (int i = 0; i<4; i++)
        cout << "i am main thread " << i << endl;
    return 0;
}

 

 

 

示例二:自解锁(构造对象时执行了枷锁,在析构对象时执行了解锁)

#include <iostream>
#include <thread>
#include <mutex>

using namespace std;

mutex m_lock;

void workFun(int index)
{

    for (int i = 0; i < 1000; i++)
    {
        lock_guard<mutex> gl(m_lock);
        //m_lock.lock();
        if (i > 500)
        {
            //m_lock.unlock();
            return;
        }
        
        cout << index << " child thread " << i << endl;
        //m_lock.unlock();

    }

}//抢占式

int main()
{
    thread t[3];
    for (int n = 0; n<3; n++)
    {
        t[n] = thread(workFun, n);
    }

    for (int n = 0; n<3; n++)
    {
        t[n].join();
    }

    for (int i = 0; i<4; i++)
        cout << "i am main thread " << i << endl;
    return 0;
}

 

上一篇:c++ 显示调用dll


下一篇:Linux 自旋锁简介