Skip to content

Instantly share code, notes, and snippets.

@jpcima
Created May 21, 2018 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpcima/6b69e216862e1a19496b2677485be3f7 to your computer and use it in GitHub Desktop.
Save jpcima/6b69e216862e1a19496b2677485be3f7 to your computer and use it in GitHub Desktop.
#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