Initialize Critical Section only once for a proces

2019-06-19 00:18发布

In a multi threaded application, is there a way to ensure that a Critical Section is initialized only once except for putting the code in DLL main() ??

5条回答
何必那么认真
2楼-- · 2019-06-19 01:03

On Windows Vista you can use the one-time initialization functions. Using One-Time Initialization shows how to use them to make sure an event is initialized only once.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-06-19 01:04

You can initialize a global critical section in DllMain for DLL_PROCESS_ATTACH (and clean up for DLL_PROCESS_DETACH).

查看更多
爷的心禁止访问
4楼-- · 2019-06-19 01:05

I'd suggest wrapping the CRITICAL_SECTION with a class that will handle the initialization and uninitialization of the critical section object in its constructor and destructor. This way, you'll be thread safe in most cases. (You'll have to make sure no one accesses the object before its constructor completes, but that's relatively easy.)

There are several common wrappers for CRITICAL_SECTION you can use. MFC's CCriticalSection is the obvious choice, but you can create your own as well.

查看更多
劳资没心,怎么记你
5楼-- · 2019-06-19 01:07

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

查看更多
Rolldiameter
6楼-- · 2019-06-19 01:08

Sure there are many many ways.

  1. Use a global variable
  2. Use a singleton instance
  3. Create it in main or some other single instance function
  4. Create it as a member var of some single instance class instance

and so on. This is no different from any other question of trying to create a single instance of some thing in your code.

查看更多
登录 后发表回答