1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
internal DWORD WINAPI win32_thread_entry(LPVOID raw)
{
// NOTE: the ThreadStart lives in the launching arena, copy it out but never free() it
ThreadStart start = *(ThreadStart *)raw;
tls_scratch_arena = ArenaCreate(MiB(64));
start.proc(start.param);
ArenaDestroy(tls_scratch_arena);
return 0;
}
internal Thread thread_launch(Arena *arena, ThreadProc *proc, void *param)
{
Thread thread = {};
ThreadStart *start = PushStruct(arena, ThreadStart);
start->proc = proc;
start->param = param;
HANDLE handle = CreateThread(NULL, 0, win32_thread_entry, start, 0, NULL);
AssertLog(handle != NULL, "failed to launch thread");
thread.data[0] = (u64)(umm)handle;
return thread;
}
internal b32 thread_join(Thread thread)
{
HANDLE handle = (HANDLE)(umm)thread.data[0];
b32 ok = WaitForSingleObject(handle, INFINITE) == WAIT_OBJECT_0;
CloseHandle(handle);
return ok;
}
internal void thread_detach(Thread thread)
{
CloseHandle((HANDLE)(umm)thread.data[0]);
}
internal void thread_set_name(String8 name)
{
// NOTE: SetThreadDescription is windows 10 1607+, look it up so older kernels still run
typedef HRESULT WINAPI SetThreadDescriptionProc(HANDLE thread, PCWSTR description);
local_persist SetThreadDescriptionProc *set_description = (SetThreadDescriptionProc *)(void *)
GetProcAddress(GetModuleHandleA("kernel32.dll"), "SetThreadDescription");
if(!set_description) return;
WCHAR wide[64] = {0};
int length = MultiByteToWideChar(CP_UTF8, 0, (const char *)name.data, (int)Min(name.size, (u64)62), wide, 63);
wide[length > 0 ? length : 0] = 0;
set_description(GetCurrentThread(), wide);
}
internal u64 thread_current_id(void)
{
return (u64)GetCurrentThreadId();
}
|