1 /* Threads.c -- multithreading library
2 2017-06-26 : Igor Pavlov : Public domain */
12 static WRes
GetError()
14 DWORD res
= GetLastError();
15 return res
? (WRes
)res
: 1;
18 static WRes
HandleToWRes(HANDLE h
) { return (h
!= NULL
) ? 0 : GetError(); }
19 static WRes
BOOLToWRes(BOOL v
) { return v
? 0 : GetError(); }
21 WRes
HandlePtr_Close(HANDLE
*p
)
32 WRes
Handle_WaitObject(HANDLE h
) { return (WRes
)WaitForSingleObject(h
, INFINITE
); }
34 WRes
Thread_Create(CThread
*p
, THREAD_FUNC_TYPE func
, LPVOID param
)
36 /* Windows Me/98/95: threadId parameter may not be NULL in _beginthreadex/CreateThread functions */
41 *p
= CreateThread(0, 0, func
, param
, 0, &threadId
);
46 *p
= (HANDLE
)_beginthreadex(NULL
, 0, func
, param
, 0, &threadId
);
50 /* maybe we must use errno here, but probably GetLastError() is also OK. */
51 return HandleToWRes(*p
);
54 static WRes
Event_Create(CEvent
*p
, BOOL manualReset
, int signaled
)
56 *p
= CreateEvent(NULL
, manualReset
, (signaled
? TRUE
: FALSE
), NULL
);
57 return HandleToWRes(*p
);
60 WRes
Event_Set(CEvent
*p
) { return BOOLToWRes(SetEvent(*p
)); }
61 WRes
Event_Reset(CEvent
*p
) { return BOOLToWRes(ResetEvent(*p
)); }
63 WRes
ManualResetEvent_Create(CManualResetEvent
*p
, int signaled
) { return Event_Create(p
, TRUE
, signaled
); }
64 WRes
AutoResetEvent_Create(CAutoResetEvent
*p
, int signaled
) { return Event_Create(p
, FALSE
, signaled
); }
65 WRes
ManualResetEvent_CreateNotSignaled(CManualResetEvent
*p
) { return ManualResetEvent_Create(p
, 0); }
66 WRes
AutoResetEvent_CreateNotSignaled(CAutoResetEvent
*p
) { return AutoResetEvent_Create(p
, 0); }
69 WRes
Semaphore_Create(CSemaphore
*p
, UInt32 initCount
, UInt32 maxCount
)
71 *p
= CreateSemaphore(NULL
, (LONG
)initCount
, (LONG
)maxCount
, NULL
);
72 return HandleToWRes(*p
);
75 static WRes
Semaphore_Release(CSemaphore
*p
, LONG releaseCount
, LONG
*previousCount
)
76 { return BOOLToWRes(ReleaseSemaphore(*p
, releaseCount
, previousCount
)); }
77 WRes
Semaphore_ReleaseN(CSemaphore
*p
, UInt32 num
)
78 { return Semaphore_Release(p
, (LONG
)num
, NULL
); }
79 WRes
Semaphore_Release1(CSemaphore
*p
) { return Semaphore_ReleaseN(p
, 1); }
81 WRes
CriticalSection_Init(CCriticalSection
*p
)
83 /* InitializeCriticalSection can raise only STATUS_NO_MEMORY exception */
88 InitializeCriticalSection(p
);
89 /* InitializeCriticalSectionAndSpinCount(p, 0); */
92 __except (EXCEPTION_EXECUTE_HANDLER
) { return 1; }