Skip to content

Instantly share code, notes, and snippets.

@pk13610
Last active May 12, 2022 12:37
Show Gist options
  • Save pk13610/10673b690b188bdf5807fa0b8c5b31e2 to your computer and use it in GitHub Desktop.
Save pk13610/10673b690b188bdf5807fa0b8c5b31e2 to your computer and use it in GitHub Desktop.
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
///////////////////////////1//1///111111/!
// crt_ begthrdex. cpp
// compile with: /MT
#define LOG_INFO(fmt, ...) { printf(fmt"\n", ##__VA_ARGS__); fflush(stdout); }
HANDLE g_hSem = NULL;
unsigned g_Counter = 0;
const static int THREAD_COUNT = 64;
struct Arguments
{
int counter;
int seq;
};
Arguments g_arguments[THREAD_COUNT] = { 0 };
unsigned _stdcall SecondThreadFunc(void* pArguments)
{
Arguments* pArg = (Arguments*)pArguments;
pArg->counter++;
unsigned tid = GetCurrentThreadId();
HFILE hFile[1024] = { 0 };
LOG_INFO("[%2d, %6d, %4d] step1, WaitForSingleobject, %p", pArg->seq, tid, pArg->counter, g_hSem);
WaitForSingleObject(g_hSem, INFINITE);
LOG_INFO("[%2d, %6d, %4d] setp2, Open", pArg->seq, tid, pArg->counter);
for (int i = 0; i < sizeof(hFile) / sizeof(HFILE); i++) {
OFSTRUCT ofstruct;
hFile[i] = OpenFile("aaa.txt", &ofstruct, OF_READWRITE);
g_Counter++;
}
Sleep(1);
LOG_INFO("[%2d, %6d, %4d] setp3, release", pArg->seq, tid, pArg->counter);
ReleaseSemaphore(g_hSem, 1, NULL);
LOG_INFO("[%2d, %6d, %4d] setp4, closeHandle", pArg->seq, tid, pArg->counter);
for (int i = 0; i < 1024; i++) {
if (hFile[i]) {
CloseHandle((HANDLE)hFile[i]);
}
}
LOG_INFO("[%2d, %6d, %4d] setp5, finished", pArg->seq, tid, pArg->counter);
_endthreadex(0);
return 0;
}
int main(int argc, char* argv[])
{
HANDLE hThread[THREAD_COUNT] = { 0 };
unsigned threadID[THREAD_COUNT];
g_hSem = CreateSemaphore(NULL, 0, THREAD_COUNT, _T("mySem"));
LOG_INFO("main, Createing second thread ...");
for (unsigned i = 0; i < THREAD_COUNT; i++) {
g_arguments[i].seq = i;
g_arguments[i].counter = 0;
hThread[i] = (HANDLE)_beginthreadex(NULL, 0, &SecondThreadFunc, (unsigned*)&g_arguments[i], 0, &threadID[i]);
}
Sleep(3000);
int release_count = 10;
LOG_INFO("main, release %d", release_count);
ReleaseSemaphore(g_hSem, release_count, NULL);
WaitForMultipleObjects(THREAD_COUNT, hThread, TRUE, INFINITE);
LOG_INFO("main, Counter should be 1000000; it is -> %d", g_Counter);
for (int i = 0; i < THREAD_COUNT; i++) {
if (hThread[i]) {
CloseHandle(hThread[i]);
}
}
if (g_hSem) {
CloseHandle(g_hSem);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment