include/mgba-util/platform/windows/threading.h (view raw)
1/* Copyright (c) 2013-2015 Jeffrey Pfau
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6#ifndef WINDOWS_THREADING_H
7#define WINDOWS_THREADING_H
8
9#include <mgba-util/common.h>
10
11#define _WIN32_WINNT 0x0600
12#include <windows.h>
13#define THREAD_ENTRY DWORD WINAPI
14typedef THREAD_ENTRY ThreadEntry(LPVOID);
15
16typedef HANDLE Thread;
17typedef CRITICAL_SECTION Mutex;
18typedef CONDITION_VARIABLE Condition;
19typedef DWORD ThreadLocal;
20
21static inline int MutexInit(Mutex* mutex) {
22 InitializeCriticalSection(mutex);
23 return GetLastError();
24}
25
26static inline int MutexDeinit(Mutex* mutex) {
27 DeleteCriticalSection(mutex);
28 return GetLastError();
29}
30
31static inline int MutexLock(Mutex* mutex) {
32 EnterCriticalSection(mutex);
33 return GetLastError();
34}
35
36static inline int MutexTryLock(Mutex* mutex) {
37 if (TryEnterCriticalSection(mutex)) {
38 return 0;
39 }
40 return 1;
41}
42
43static inline int MutexUnlock(Mutex* mutex) {
44 LeaveCriticalSection(mutex);
45 return GetLastError();
46}
47
48static inline int ConditionInit(Condition* cond) {
49 InitializeConditionVariable(cond);
50 return GetLastError();
51}
52
53static inline int ConditionDeinit(Condition* cond) {
54 // This is a no-op on Windows
55 UNUSED(cond);
56 return 0;
57}
58
59static inline int ConditionWait(Condition* cond, Mutex* mutex) {
60 SleepConditionVariableCS(cond, mutex, INFINITE);
61 return GetLastError();
62}
63
64static inline int ConditionWaitTimed(Condition* cond, Mutex* mutex, int32_t timeoutMs) {
65 SleepConditionVariableCS(cond, mutex, timeoutMs);
66 return GetLastError();
67}
68
69static inline int ConditionWake(Condition* cond) {
70 WakeAllConditionVariable(cond);
71 return GetLastError();
72}
73
74static inline int ThreadCreate(Thread* thread, ThreadEntry entry, void* context) {
75 *thread = CreateThread(NULL, 0, entry, context, 0, 0);
76 return GetLastError();
77}
78
79static inline int ThreadJoin(Thread* thread) {
80 DWORD error = WaitForSingleObject(*thread, INFINITE);
81 if (error == WAIT_FAILED) {
82 return GetLastError();
83 }
84 return 0;
85}
86
87static inline int ThreadSetName(const char* name) {
88 UNUSED(name);
89 return -1;
90}
91
92static inline void ThreadLocalInitKey(ThreadLocal* key) {
93 *key = TlsAlloc();
94}
95
96static inline void ThreadLocalSetKey(ThreadLocal key, void* value) {
97 TlsSetValue(key, value);
98}
99
100static inline void* ThreadLocalGetValue(ThreadLocal key) {
101 return TlsGetValue(key);
102}
103
104#endif