Initialize a critical section only once for a process

In a multi-threaded application, is there a way to guarantee that the critical section will be initialized only once, except that it is placed in the main () DLL ??

+6
windows dll winapi com
source share
5 answers

I would suggest wrapping CRITICAL_SECTION with a class that will handle the initialization and non-initialization of the critical section object in its constructor and destructor. Thus, in most cases you will be thread safe. (You will need to make sure that no one gets access to the object until its constructor completes, but it's relatively simple.)

There are several common wrappers for CRITICAL_SECTION that you can use. MFC CCriticalSection is an obvious choice, but you can also create your own.

+3
source share

In Windows Vista, you can use one-time initialization functions. Using one-time initialization shows how to use them to make sure that the event is initialized only once.

+5
source share

Of course, there are many ways.

  • Use global variable
  • Use singleton instance
  • Create it in the main or some other function of one instance
  • Create it as a member of a var instance of a single instance of an instance of an instance

etc. This is no different than any other question about trying to create one instance of a thing in your code.

+1
source share

You can also use a wrapper class and declare a global object of this class. The constructor of the global object will be called only once at startup.

0
source share

You can initialize the global critical section in DllMain for DLL_PROCESS_ATTACH (and clear it for DLL_PROCESS_DETACH ).

0
source share

All Articles