Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize Critical Section only once for a process

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() ??

like image 308
atVelu Avatar asked Apr 07 '09 07:04

atVelu


People also ask

Is critical section recursive?

By default, a CRITICAL_SECTION object is recursive.

What is the maximum number of threads that could be waiting to access the critical section?

No more than one thread can be in its critical section at any one time. A thread which dies in its critical non-critical section will not affect the others' ability to continue.

How do we Create a critical section?

Typically, this is done by simply declaring a variable of type CRITICAL_SECTION. Before the threads of the process can use it, initialize the critical section by using the InitializeCriticalSection or InitializeCriticalSectionAndSpinCount function.

When to use critical section in c++?

Critical Section: When more than one processes access the same code segment that segment is known as the critical section. The critical section contains shared variables or resources which are needed to be synchronized to maintain the consistency of data variables.


3 Answers

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.

like image 119
freak Avatar answered Nov 15 '22 07:11

freak


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.

like image 26
eran Avatar answered Nov 15 '22 06:11

eran


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.

like image 32
1800 INFORMATION Avatar answered Nov 15 '22 07:11

1800 INFORMATION