windows 为一个进程只初始化一次临界区
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/724560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initialize Critical Section only once for a process
提问by atVelu
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() ??
在多线程应用程序中,除了将代码放入 DLL main() 之外,有没有办法确保临界区仅初始化一次?
采纳答案by eran
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.)
我建议将 CRITICAL_SECTION 包装在一个类中,该类将在其构造函数和析构函数中处理临界区对象的初始化和取消初始化。这样,在大多数情况下,您将是线程安全的。(您必须确保在其构造函数完成之前没有人访问该对象,但这相对容易。)
There are several common wrappers for CRITICAL_SECTION you can use. MFC's CCriticalSectionis the obvious choice, but you can create your own as well.
您可以使用几种常见的 CRITICAL_SECTION 包装器。MFC 的CCriticalSection是显而易见的选择,但您也可以创建自己的。
回答by freak
On Windows Vista you can use the one-time initialization functions. Using One-Time Initializationshows how to use them to make sure an event is initialized only once.
在 Windows Vista 上,您可以使用一次性初始化功能。使用一次性初始化展示了如何使用它们来确保一个事件只初始化一次。
回答by 1800 INFORMATION
Sure there are many many ways.
当然有很多很多方法。
- Use a global variable
- Use a singleton instance
- Create it in main or some other single instance function
- Create it as a member var of some single instance class instance
- 使用全局变量
- 使用单例
- 在 main 或其他一些单实例函数中创建它
- 将其创建为某个单实例类实例的成员 var
and so on. This is no different from any other question of trying to create a single instance of some thing in your code.
等等。这与尝试在代码中创建某个事物的单个实例的任何其他问题没有什么不同。
回答by sharptooth
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.
您还可以使用包装类并声明该类的全局对象。全局对象的构造函数在启动时只会被调用一次。
回答by Richard
You can initialize a global critical section in DllMain
for DLL_PROCESS_ATTACH
(and clean up for DLL_PROCESS_DETACH
).
您可以在DllMain
for 中初始化全局临界区DLL_PROCESS_ATTACH
(并清理 for DLL_PROCESS_DETACH
)。