How to create a Singleton in C?

前端 未结 6 1195
感动是毒
感动是毒 2020-12-08 01:11

What\'s the best way to create a singleton in C? A concurrent solution would be nice.

I am aware that C isn\'t the first language you would use for a singleton.

6条回答
  •  庸人自扰
    2020-12-08 01:33

    EDIT: My answer presumes the singleton you are creating is somewhat complex and has a multi-step creation process. If it's just static data, go with a global like others have suggested.

    A singleton in C will be very weird . . . I've never seen an example of "object oriented C" that looked particularly elegant. If possible, consider using C++. C++ allows you to pick and choose which features you want to use, and many people just use it as a "better C".

    Below is a pretty typical pattern for lock-free one-time initialization. The InterlockCompareExchangePtr atomically swaps in the new value if the previous is null. This protects if multiple threads try to create the singleton at the same time, only one will win. The others will delete their newly created object.

    MyObj* g_singleton; // MyObj is some struct.
    
    MyObj* GetMyObj()
    {
        MyObj* singleton;
        if (g_singleton == NULL)
        {
            singleton = CreateNewObj();
    
            // Only swap if the existing value is null.  If not on Windows,
            // use whatever compare and swap your platform provides.
            if (InterlockCompareExchangePtr(&g_singleton, singleton, NULL) != NULL)
            {
                  DeleteObj(singleton);
            }
        }
    
        return g_singleton;
    }
    
    DoSomethingWithSingleton(GetMyObj());
    

提交回复
热议问题