SHGlobalCounterGetValue

This function reads a global counter.

Declaration

LONG SHGlobalCounterGetValue (HANDLE hCounter);

Parameters

The hCounter argument provides a handle to the global counter, as obtained through some earlier call to either SHGlobalCounterCreate or SHGlobalCounterCreateNamed.

Return Value

The function returns the current value of the given counter.

Behaviour

The global counter is implemented as the release count in a semaphore. This function is implemented as two operations on the release count:

  1. a ReleaseSemaphore, to increment the release count and learn its pre-incremented value;
  2. a WaitForSingleObject, to decrement the release count.

One problem with this algorithm is that if the counter is already at MAXLONG (which, admittedly, is very unlikely in practice), then the function cannot first increment the release count and ends up misreading the counter. It returns zero.

As an aside, imagine two threads that share access to some global counter and each execute a loop that only ever calls this SHGlobalCounterGetValue function to read the counter. Then, because of the two-step process noted above, each thread may see that the counter sometimes changes in value, even though neither ever calls SHGlobalCounterIncrement or SHGlobalCounterDecrement to change the counter.

Availability

The SHGlobalCounterGetValue function is exported from SHLWAPI as ordinal 223 in version 5.00 and higher.

Though this function dates from as long ago as 1999, it was still not documented by Microsoft in the MSDN Library at least as late as the CD edition dated January 2004.