You might get away with named semaphore. Semaphore is basically a count, it is here to allow developers limit the number of thread/processes that are accessing some resource. Usually it works like that
- You create a semaphore with maximum count N.
- N threads call waiting function on it,
WaitForSingleObject
or similar and each of them go on without waiting. Each time internal semaphore counter goes down.
- N+1 thread also calls waiting function but because internal counter of our semaphore is 0 now, it has to wait.
- One of our first N threads releases the semaphore by calling
ReleaseSemaphore
function. This function increments internal counter of semaphore.
- Our waiting thread don't have to wait now, so it resumes but semaphore counter goes back to 0.
I don't think this is how you want to use it though. So, instead, you should:
- Create named semaphore with initial counter set to zero.
- When application start, immediately release it, increasing the counter. You'll get previous counter value during that call.
- When application ends, call
WaitForSingleObject(hSemaphore, 0)
, decreasing the counter. 0 means you don't want to wait.
This is all quite easy.
In C++
//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);
In C#
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);
Names and BIG_NUMBERs should be the same obviously.
If this is not sufficient for your task, you will have to look into shared memory and lock access to it though named mutex, but that is a little bit more complicated.