Different Between Static Mutext and Not Static Mutex

六月ゝ 毕业季﹏ 提交于 2020-01-04 05:52:07

问题


I have a code in .cpp

namespapce A
{
    namespace
    {
        static CMutex initMutex;
    }

    void init()
    {
        //code here
    }

    void uninit()
    {
        //code here
    }
}

What is the different if I remove the static in the mutex and if there is a static? And what is the use of the static?

Thanks!


回答1:


If mutex is static and if it would have been in the header and that header included in 2 cpp files(2 translational units), the lock applied by the code in first file will not be seen by the second file which is dangerous. This is because the 2 units has separate static of the mutex. In that case a global mutex is preferable.

If this is C++ then use RAII mechanism to manage mutex lock and unlock. THis is c++, where is the class? Encapsulate things into a class.

RAII example (basic one, things can be encapsulated into class): http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization




回答2:


You are Kind of mixing up C and C++. The keyword static in C has the intention to narrow the scope of a variable down to the translation unit. You could define it globally in the translation unit, but it was not visible to other translation-units. Bjarne Stroustrup recommends to use anonymous namespaces in C++ instead of using static like in C.

From this post it says

The C++ Standard reads in section 7.3.1.1 Unnamed namespaces, paragraph 2:

The use of the static keyword is deprecated when declaring objects 
in a namespace scope, the unnamed-namespace provides a superior alternative.

Static only applies to names of objects, functions, and anonymous unions, not to type declarations.




回答3:


static merely does two things:

  • makes a variable to exist for the entire life of a program (but this is global level, so anything here exist for the whole program life!)

  • makes a variable visible only in the translation unit it is declared (but this apply to whatever is in an anonymous namespace).

So, in fact, in this particular context, static does nothing.



来源:https://stackoverflow.com/questions/15828890/different-between-static-mutext-and-not-static-mutex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!