I wrote a simple example of using a semaphore, but sometimes messages from the first thread are not displayed. What the problem?
#include <iostream>
#include <windows.h>
#include <process.h>
HANDLE Semaphore;
void test1(void*) {
WaitForSingleObject(Semaphore, INFINITE);
std::cout << "Thread1: access granted";
_endthread();
}
void test2(void*) {
ReleaseSemaphore(Semaphore, 1, NULL);
_endthread();
}
int main() {
Semaphore = CreateSemaphore(NULL, 0, 1, NULL);
_beginthread(test1, 2048, NULL);
_beginthread(test2, 2048, NULL);
CloseHandle(Semaphore);
}