Question

I recently started using C++ instead of Delphi. And there are some things that seem to be quite different. For example I don't know how to initialize variables like Semaphores and CriticalSections. By now I only know 2 possible ways: 1. Initializing a Critical Section in the constructor is stupid since every instance would be using its own critical section without synchronizing anything, right? 2. Using a global var and initializing it when the form is created seems not to be the perfect solution, as well. Can anyone tell me how to achieve this?

Just a short explanation for what I need the Critical Section : I'd like to fill a ListBox from different threads. The Semaphore : Different threads are moving the mouse, this shouldn't be interrupted.

Thanks!

Was it helpful?

Solution

Contrary to Delphi, C++ has no concept of unit initialization/finalization (but you already found out about that).

What we are left with is very little. You need to distinguish two things:

  • where you declare your variable (global, static class member, class member, local to a function, static in a function -- I guess that covers it all)
  • where you initialize your variable (since you are concerned with a C API you have to call the initialization function yourself)

Fact is, in your case it hardly matters where you declare your variable as long as it is accessible to all the other parts of your program that need it, and the only requirement as to where you should initialize it is: before you actually start using it (which implies, before you start other threads).

In your case I would probably use a singleton pattern. But C++ being what it is, singletons suffer from race condition during their initialization, there is no clean way around that. So, in addition to your singleton, you should ensure that it is correctly created before you start using it in multithreaded context. A simple call to getInstance() at the start of your main() will do the trick (or anywhere else you see fit). As you see, this takes only care of where you declare your variable, not where you initialize it, but unfortunately C++ has important limitations when it comes to multithreading (it is under-specified) so there is no way around that.

To sum it up: just do what you want (as long as it works) and stop worrying.

OTHER TIPS

In my opinion you only need a critical section to synchronize updates to a list box from various threads. Mouse will keep moving. Semaphore is not fitting the solution. You initialize the critical section in you class constructor. where the list box is. Write a method to update the listbox.

//psudo code
UpdateListBox()
{
 //enter critical section
 //update
 //leave critical section
}

All the threads will call this method to update the listbox.

information about critical section is here http://msdn.microsoft.com/en-us/library/windows/desktop/ms683472%28v=vs.85%29.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top