Created
June 20, 2018 19:26
-
-
Save Donpedro13/bd0cef2b962acdc13a40182010005648 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <process.h> | |
#include <windows.h> | |
CRITICAL_SECTION g_cs; | |
static unsigned int ThreadMain (void* /*context*/) | |
{ | |
EnterCriticalSection (&g_cs); | |
std::cout << "Background thread locked critical section" << std::endl; | |
LeaveCriticalSection (&g_cs); | |
std::cout << "Background thread unlocked critical section" << std::endl; | |
return 0; | |
} | |
int main () | |
{ | |
Sleep (5000); | |
// Init | |
InitializeCriticalSection (&g_cs); | |
// Sleep for 1 seconds | |
Sleep (1000); | |
// Burn CPU for 3 seconds | |
static volatile double dummy1 = 3.33f; | |
static volatile uint16_t dummy2 = 35; | |
const ULONGLONG tTarget = GetTickCount64 () + 3 * 1000; | |
while (GetTickCount64 () <= tTarget) { | |
dummy1 *= dummy2; | |
dummy1 /= dummy2; | |
} | |
// Lock CS | |
EnterCriticalSection (&g_cs); | |
std::cout << "Main thread locked critical section" << std::endl; | |
// Launch thread | |
HANDLE hThread = reinterpret_cast<HANDLE> (_beginthreadex (nullptr, | |
0, | |
ThreadMain, | |
nullptr, | |
0, | |
nullptr)); | |
// Unlock CS after sleep | |
Sleep (1000); | |
LeaveCriticalSection (&g_cs); | |
std::cout << "Main thread unlocked critical section" << std::endl; | |
// Wait for the background thread | |
WaitForSingleObject (hThread, INFINITE); | |
// DeInit | |
DeleteCriticalSection (&g_cs); | |
/*std::cout << "Waiting 10 seconds, then terminating..." << std::endl; | |
Sleep (10'000);*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment