静态锁问题

在类中声明了静态成员变量锁后,相当于定义了该类的全局锁,该类的每一个对象这个锁都有效,共用同一个锁。如例子所示

(1)仅声明静态锁,不进行调用

#include "stdafx.h"
#include "thread"
#include "iostream"
#include "mutex"
 
class Address{
public:
    static std::mutex grobal_mutex;
    std::mutex mtx;
    Address(int n_):n(n_){}
    int n;
    void add()
    {
        std::unique_lock<std::mutex> ulck(mtx);
        for (int i = 0; i < 1; i++)
        {
            std::cout<< "n = "<< n++ << std::endl;
        }
    }
 
};
std::mutex Address::grobal_mutex;
Address a3(0);
void func1()
{
    Address a1(5);
    for (int i = 0; i < 5; i++)
    {
        a1.add();
        std::cout<< "i1 = "<< i << std::endl;
    }
   
}
void func2()
{
    Address a2(10);
    for (int i = 0; i < 5; i++)
    {
        a2.add();
        std::cout<< "i2 = "<< i << std::endl;
    }
}
 
int _tmain(int argc, _TCHAR* argv[])
{
    std::thread th1(func1);
    std::thread th2(func2);
    th1.join();
    th2.join();
    return 0;
}

结果:

n = n = 105
 
i1 = 0
i2 = 0
n = 6
n = 11
i2 = 1
n = 12
i2 = 2
n = 13
i2 = 3
n = 14
i2 = 4
i1 = 1
n = 7
i1 = 2
n = 8
i1 = 3
n = 9
i1 = 4


从结果可以看出只声明静态锁grobal_mutex并在类外进行内存分配,不进行调用,该静态锁就不会起作用。而且从这个例子中我们可以明显看到非静态锁在两个不同对象调用时,不会起作用。

(2)声明静态锁并调用它

#include "stdafx.h"
#include "thread"
#include "iostream"
#include "mutex"
 
class Address{
public:
    static std::mutex grobal_mutex;
    std::mutex mtx;
    Address(int n_){}
    static int n;
    static void add()
    {
        std::unique_lock<std::mutex> ulck(grobal_mutex);
        for (int i = 0; i < 1; i++)
        {
            std::cout<< "n = "<< n++ << std::endl;
        }
    }
};
int Address::n = 0;
std::mutex Address::grobal_mutex;
Address a3(0);
void func1()
{
    //std::unique_lock<std::mutex> x(Address::grobal_mutex);
    Address a1(5);
    for (int i = 0; i < 5; i++)
    {
        a3.add();
        std::cout<< "i1 = "<< i << std::endl;
    }
   
}
void func2()
{
    Address a2(10);
    //std::unique_lock<std::mutex> x(a1.grobal_mutex);
    for (int i = 0; i < 5; i++)
    {
        a3.add();
        std::cout<< "i2 = "<< i << std::endl;
    }
}
int _tmain(int argc, _TCHAR* argv[])
{
    std::thread th1(func1);
    std::thread th2(func2);
    th1.join();
    th2.join();
    return 0;
}

结果:

n = n = 105
 
i1 = 0
i2 = 0
n = 6
n = 11
i2 = 1
n = 12
i2 = 2
n = 13
i2 = 3
n = 14
i2 = 4
i1 = 1
n = 7
i1 = 2
n = 8
i1 = 3
n = 9
i1 = 4


posted @ 2017-08-04 09:29  糖甜不粘牙  阅读(231)  评论(0编辑  收藏  举报