8 /* Since cothread_t is a void pointer it must contain an address. We can't return a reference to a local variable
9 * because it would go out of scope, so we create a static variable instead so we can return a reference to it.
11 static int32_t active_thread_id = -1;
14 cothread_t co_active()
16 active_thread_id = GetThreadId();
17 return &active_thread_id;
20 cothread_t co_create(unsigned int size, void (*entrypoint)(void))
22 /* Similar scenario as with active_thread_id except there will only be one active_thread_id while there could be many
23 * new threads each with their own handle, so we create them on the heap instead and delete them manually when they're
24 * no longer needed in co_delete().
27 int32_t new_thread_id;
28 cothread_t handle = malloc(sizeof(cothread_t));
29 void *threadStack = (void *)malloc(size);
34 thread.stack_size = size;
36 thread.func = (void *)entrypoint;
37 thread.stack = threadStack;
39 thread.initial_priority = 1;
41 new_thread_id = CreateThread(&thread);
42 StartThread(new_thread_id, NULL);
43 *(uint32_t *)handle = new_thread_id;
47 void co_delete(cothread_t handle)
49 TerminateThread(*(uint32_t *)handle);
50 DeleteThread(*(uint32_t *)handle);
54 void co_switch(cothread_t handle)
56 WakeupThread(*(uint32_t *)handle);
57 /* Sleep the currently active thread so the new thread can start */