Cthulhu  0.2.10
Cthulhu compiler collection
thread.c
Go to the documentation of this file.
1 // SPDX-License-Identifier: LGPL-3.0-only
2 #include "os_common.h"
3 
4 #include "base/panic.h"
5 
6 // TODO: naming threads requires some pretty arcane win32 calls
7 
8 static DWORD WINAPI thread_fn(LPVOID param)
9 {
10  os_thread_t *thread = param;
11 
12  return thread->fn(thread->arg);
13 }
14 
16 os_error_t os_thread_init(
17  os_thread_t *thread,
18  const char *name,
19  os_thread_fn_t fn,
20  void *arg)
21 {
22  CTASSERT(thread != NULL);
23  CTASSERT(name != NULL);
24  CTASSERT(fn != NULL);
25 
26  thread->name = name;
27  thread->fn = fn;
28  thread->arg = arg;
29  thread->impl = NULL;
30 
31  DWORD id = 0;
32 
33  HANDLE handle = CreateThread(NULL, 0, thread_fn, thread, 0, &id);
34 
35  if (handle == INVALID_HANDLE_VALUE)
36  {
37  return GetLastError();
38  }
39 
40  thread->impl = handle;
41  thread->id = id;
42 
43  return eOsSuccess;
44 }
45 
47 os_error_t os_thread_join(os_thread_t *thread, os_status_t *status)
48 {
49  CTASSERT(thread != NULL);
50  CTASSERT(status != NULL);
51 
52  if (WaitForSingleObject(thread->impl, INFINITE) != WAIT_OBJECT_0)
53  {
54  return GetLastError();
55  }
56 
57  DWORD result = 0;
58 
59  if (GetExitCodeThread(thread->impl, &result) == 0)
60  {
61  return GetLastError();
62  }
63 
64  *status = result;
65 
66  return eOsSuccess;
67 }
68 
70 {
71  return GetCurrentThreadId();
72 }
#define STA_DECL
sal2 annotation on function implementations to copy annotations from the declaration
os_thread_id_t os_get_thread_id(void)
get the current thread id
Definition: thread.c:56
unsigned os_status_t
thread return code
Definition: core.h:71
size_t os_thread_id_t
thread id
Definition: core.h:75
os_exitcode_t(* os_thread_fn_t)(void *arg)
Definition: os.h:73
#define CTASSERT(expr)
assert a condition, prints the condition as a message
Definition: panic.h:130
STA_DECL os_error_t os_thread_join(os_thread_t *thread, os_status_t *status)
Definition: thread.c:39
STA_DECL os_error_t os_thread_init(os_thread_t *thread, const char *name, os_thread_fn_t fn, void *arg)
Definition: thread.c:14
@ eOsSuccess
Definition: posix.h:24
a thread handle
Definition: os.h:79
os_thread_id_t id
Definition: os.h:88
os_thread_fn_t fn
Definition: os.h:83
const char * name
Definition: os.h:81
void * arg
Definition: os.h:84
os_thread_impl_t impl
Definition: os.h:87