Created
May 21, 2018 16:18
-
-
Save jpcima/6b69e216862e1a19496b2677485be3f7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <windows.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <vector> | |
static CRITICAL_SECTION cs; | |
DWORD WINAPI thread_run(void *user_data) | |
{ | |
unsigned i = (unsigned)user_data; | |
EnterCriticalSection(&cs); | |
printf("This is thread %u\n", i); | |
Sleep(3000); | |
LeaveCriticalSection(&cs); | |
return 0; | |
} | |
int main() | |
{ | |
if (0) { | |
InitializeCriticalSection(&cs); | |
printf("InitializeCriticalSection\n"); | |
} | |
else { | |
SetLastError(0); | |
unsigned spin_count = 100; | |
BOOL b = InitializeCriticalSectionAndSpinCount(&cs, spin_count); | |
DWORD e = GetLastError(); | |
printf("InitializeCriticalSectionWithSpinCount %u -> (%s,error=%u)\n", | |
spin_count, b ? "TRUE" : "FALSE", e); | |
} | |
std::vector<HANDLE> hThreads; | |
for (unsigned i = 0; i < 10; ++i) { | |
DWORD idThread = 0; | |
DWORD stackSize = 64 * 1024; | |
HANDLE hThread = CreateThread( | |
NULL, stackSize, &thread_run, (void *)i, 0, &idThread); | |
if (!hThread) { | |
DWORD e = GetLastError(); | |
printf("CreateThread error=0x%x\n", e); | |
abort(); | |
} | |
hThreads.push_back(hThread); | |
} | |
for (HANDLE hThread : hThreads) { | |
WaitForSingleObject(hThread, INFINITE); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment