C # and C ++ Synchronization between processes

We have 2 applications. One is written in C #, and the other in C ++. We need to maintain a counter (in memory) shared by these processes. Each time one of these applications is launched, it must check this counter and increase it, and each time the application is turned off, it is necessary to decrease the counter. If the application crashes or shuts down using the task manager, we also need the counter to decrease.
We thought about using one of the OS synchronization objects, such as MUTEX.
My question is: which synchronization object is best for the cross process (when it is C # and other C ++)

I hope my question was clear.
Many thanks,

Adi barda

+5
source share
3 answers

You can leave with a semaphore. A semaphore is basically an account, here you can allow developers to limit the number of threads / processes that access a certain resource. It usually works like

  • You create a semaphore with a maximum number of N.
  • N threads call a wait function on it, WaitForSingleObjector the like, and each of them continues without waiting. Each time the internal semaphore counter goes down.
  • Thread N + 1 also calls the wait function, but since the internal counter of our semaphore is 0, it must wait.
  • N , ReleaseSemaphore. .
  • , , 0.

, . , :

  • , .
  • , , . .
  • , WaitForSingleObject(hSemaphore, 0), . 0 , .

.

++

//create semaphore
HANDLER hSemaphore = CreateSemaphore(NULL, 0, BIG_NUMBER, "My cool semaphore name");
//increase counter
LONG prev_counter;
ReleaseSemaphore(hSemaphore, 1, &prev_counter);
//decrease counter
WaitForSingleObject(hSemaphore, 0);

#

using System.Threading;
//create semaphore
Semaphore sem = new Semaphore(0, BIG_NUMBER, "My cool semaphore name");
//increase counter
int prev_counter = sem.Release(); 
//decrease counter
sem.WaitOne(0);

BIG_NUMBER .

, , mutex, .

+9

, named (CreateSemaphore): http://msdn.microsoft.com/en-us/library/ms682438(VS.85).aspx ++, /.

# System.Threading.Semaphore.

+1

.net/#.

.net, ++, #..

+1

All Articles