When using a Semaphore synchronization object sometimes you would like to know how many "aquires" are left to be done. Therefore there's the NtQuerySemaphore function which resides in NTDLL.DLL.
typedef struct _SEMAINFO { UINT Count; UINT Limit; } SEMAINFO, *PSEMAINFO;
#define SEMAQUERYINFOCLASS 0 typedef long (WINAPI *NtQuerySemaphorePtr)(HANDLE Handle, UINT InfoClass, PSEMAINFO SemaInfo, UINT InfoSize, PUINT RetLen); NtQuerySemaphorePtr NtQuerySemaphore = NULL; UINT WINAPI QuerySemaphore(HANDLE hSemaphore) { SEMAINFO SemInfo; UINT RetLen; NtQuerySemaphore(hSemaphore, SEMAQUERYINFOCLASS, &SemInfo, sizeof(SemInfo), &RetLen); // You can check return value if you like. return SemInfo.Count; }
// Init code: HMODULE g_ntdll = LoadLibrary("ntdll.dll"); NtQuerySemaphore = (NtQuerySemaphorePtr)GetProcAddress(g_ntdll, "NtQuerySemaphore");
// Usage example: HANDLE h = CreateSemaphore(NULL, 4, 5, "mysem"); WaitForSingleObject(h, 0); WaitForSingleObject(h, 0); WaitForSingleObject(h, 0); printf("Semaphore has been acquired %d times.\n", 4-QuerySemaphore(h)); ReleaseSemaphore(h, 3, NULL); CloseHandle(h);
// Destroy code: FreeLibrary(g_ntdll);
|