Skip to content
Multithreading

Multithreading

1. Introduction

There is a preemptive multithreading system in libnds that applications can use for different reasons:

  • To maximize CPU usage in applications that have a lot of wait loops until some event happens.
  • To support games in which the rendering code can run at a different frame rate than the physics code.
  • To allow using libraries that expect a multithreaded environment, like lwIP (used in DSWiFi).
  • To make it possible to load files from NitroFS or FAT asynchronously. It’s possible to use DLDI from the ARM7 (and the SD card of DSi consoles can only be read from the ARM7). Multithreading makes it possible to let an ARM9 thread wait for the ARM7 to finish reading or writing while doing something else in the ARM9.

However, multithreading (and, in particular, preemptive multithreading) is infamous for causing lots of very hard-to-debug issues in applications. Any application that has more than one user thread needs to be very careful to protect all shared resources with mutexes or semaphores.

You also need to consider that many parts of libnds aren’t thread-safe. For more details, check the section about preemption below.

2. Creating threads

In most cases you just want to create a thread and let libnds deal about the low-level allocation details. In that case you can use cothread_create():

#include <nds.h>

// A function entrypoint is a function that returns `int` and takes a `void *`
// as an argument.
int my_entrypoint(void *arg)
{
    // When a thread is created with cothread_create() it's possible to pass an
    // argument. This argument is received by the user handler in `arg`, and it
    // can point to anything you want. It can even be an integer value casted to
    // `void *`.

    // ...

    return 0;
}

int main(int argc, char *argv[])
{
    cothread_t id = cothread_create(
                        my_entrypoint,  // Thread user entrypoint
                        (void *)2,      // Pass 2 as argument to the entrypoint
                        0,              // Stack size (if 0 use the default size)
                        0);             // Flags

    // ...
}

You can pass a combination of flags to libnds depending on what you need: COTHREAD_DETACHED, COTHREAD_CONTEXT_IN_DTCM, etc. They are described in detail in other sections but, for example, you can do this if you want to create a fast thread that runs for a couple of seconds alongside the main thread:

cothread_create(my_entrypoint, NULL, 0,
                COTHREAD_DETACHED | COTHREAD_CONTEXT_IN_ITCM | COTHREAD_STACK_IN_ITCM);

Check the following example to see how to create multiple threads: examples/cothread/many_threads.

3. Detached and non-detached threads

A non-detached thread runs until completion. When it finishes, the value returned by the user function is preserved. The user is responsible for getting this value and cleaning up the resources used by the thread. For example:

cothread_t id = cothread_create(my_entrypoint, NULL, 0, 0);

// The thread runs...

while (!cothread_has_joined(id))
{
    // Do stuff while waiting...
    cothread_yield();
}

int exit_code = cothread_get_exit_code(id);

if (!dothread_delete(id))
{
    printf("Failed to free thread resources\n");
    while (1);
}

printf("The thread finished successfully: %d\n", exit_code);

If you don’t call cothread_delete() after the thread has finished the application will leak memory.

If you don’t care about the exit code, you can just use a detached thread instead:

cothread_t id = cothread_create(my_entrypoint, NULL, 0, COTHREAD_DETACHED);

When it finishes, the threading system will free the resources allocated by cothread_create(), so you don’t need to remember the thread ID after creating the thread.

Note that it isn’t possible to detect if a detached thread has finished with cothread_has_joined(), and it isn’t possible to read the exit code of a detached thread with cothread_get_exit_code().

This is a practical example of using multiple detached threads: examples/cothread/detached_threads.

4. Yielding

The main advantage of multithreaded applications is that loops that hang the application until something happens become opportunities to switch to a different thread. For example, if the ARM9 asks the ARM7 to read a block from the SD card, instead of waiting in a loop until the ARM7 has replied it can just yield and give the opportunity to other threads to do some work. If everything goes well, when the original thread resumes execution, the ARM7 will have finished reading the SD card. The result is that the ARM9 been able to do some useful work instead of waiting in a loop.

You can’t yield from an interrupt handler.

You can yield in three different ways.

4.1 Yield without sleep

cothread_yield() makes the thread yield, but it doesn’t declare any specific event to wait for. The scheduling code will resume the thread as soon as it gets the chance. If you want the CPU to enter low-power mode, you shouldn’t use cothread_yield(). For this reason, this function is only really useful for threads that need to wait for a short period of time and they want to let other threads to do some work in the meantime.

4.2 Yield and wait for an interrupt

cothread_yield_irq() and cothread_yield_irq_aux() make the thread yield and sleep until the specified IRQ (or AUX IRQ in the case of ARM7) happens. If the IRQ has happened before calling the yield function, the thread never goes to sleep, it’s scheduled right away.

It’s possible to specify a combination of IRQs (for example, you can wait for IRQ_TIMER0 | IRQ_VBLANK). You can even wait for any interrupt by using IRQ_ALL.

A very common way to synchronize the application loop to the screen refresh is to call cothread_yield_irq(IRQ_VBLANK) instead of swiWaitForVBlank().

You can see an example of waiting for IRQ_VBLANK here: examples/cothread/sync_to_vbl.

You need to be careful when yielding for an IRQ. For example, your code may do something like this:

int my_thread(void *arg)
{
    while (1)
    {
        while (1)
        {
            if (!fifoCheckDatamsg(FIFO_USER_01))
                break;

            // Handle a message
        }

        // (*)

        // Wait for more FIFO messages
        cothread_yield_irq(IPC_FIFO_RECV_NOT_EMPTY_IRQ);
    }
}

This code is potentially problematic. If there are no messages left to handle in channel FIFO_USER_01, the loop will end. If the IPC_FIFO_RECV_NOT_EMPTY_IRQ interrupt happens right then, cothread_yield_irq() will see that there are no threads waiting for that interrupt and it will save it. When cothread_yield_irq() is called, it will reactivate the thread right away. If this is the only thread that wants to wait for this IRQ, it will all work.

However, if there are two threads waiting for IPC_FIFO_RECV_NOT_EMPTY_IRQ, and the other thread is waiting for that interrupt, our sample thread won’t be reactivated unless another instance of the interrupt is handled.

If you want to avoid this issue in all situations, you need to modify your code this way:

int my_thread(void *arg)
{
    while (1)
    {
        cpsrDisableInterrupts();

        while (1)
        {
            if (!fifoCheckDatamsg(FIFO_USER_01))
                break;

            cpsrEnableInterrupts();

            // Handle a message
        }

        // (*)

        // Wait for more FIFO messages
        cothread_yield_irq(IPC_FIFO_RECV_NOT_EMPTY_IRQ);
    }
}

Basically, the piece of code that checks if there’s work to do needs to be in the same critical section (section with IRQs disabled) than the code that calls cothread_yield_irq(). Interrupts are re-enabled automatically when a thread resumes (the same way as calling cpsrEnableInterrupts()), so you need to disable them yourself every time the thread resumes.

4.3 Yield and wait for a signal

cothread_yield_signal() makes the thread yield and sleep until another thread sends a signal with the same ID with function cothread_send_signal().

Signals with bit 31 set are reserved by libnds. Users are allowed to use values 0x00000000 to 0x7FFFFFFF.

This code shows two threads. One of them writes 1 to a variable and sends a signa. The other one waits until that signal ID is received and then prints the value of the variable:

const uint32_t signal_id = 1234;

volatile int value = 0;

int thread_one(void *arg)
{
    cothread_yield_signal(signal_id);

    printf("%d", value);

    return 0;
}

int thread_two(void *arg)
{
    value = 1;

    cothread_send_signal(signal_id);

    return 0;
}

You also need to use cpsrDisableInterrupts() as explained for cothread_yield_irq() in the previous section. The main difference between cothread_yield_irq() and cothread_yield_signal() is that unhandled signals are ignored instead of keeping track of them.

If you want to see a more elaborate example, check this: examples/cothread/wait_for_signal.

4.4 Yield and wait for interrupts or signals

cothread_yield_irq_or_signal() combines the effect of cothread_yield_irq() and cothread_yield_signal(). The thread sleeps until any requested interrupt happens or the signal ID is received.

This is useful for threads that can wait for a specific event, but need to have a timeout in case the event is never received. The interrupt it waits for can be any of the timer interrupts, the VBL interrupt, etc.

5. Preemption

Threads can be paused even without manual calls to the yield functions. Whenever an interrupt happens, execution of the current thread stops and the global interrupt dispatcher starts to run. First, it calls the user interrupt handler (if any) and it unblocks any thread that was waiting for that interrupt. When the dispatcher has finished doing all of its work, it saves the context of the currently running thread and it switches to the next thread that has been scheduled.

If there are nested interrupts, only the top-level interrupt causes a thread context switch. Nested interrupts don’t cause more switches.

This is a very powerful feature that can let you optimize CPU usage if it’s used correctly, but it can also cause hard-to-debug issues. It’s also a behaviour that is required for libnds to work correctly, as some important systems (FIFO, WiFi) depend on it to work correctly.

The main issue with preemption is that you need to be careful about any resources that are shared between different threads. For example, if you keep an array of messages that thread A writes and thread B reads, you need to make sure that thread A doesn’t write messages in an order that can cause issues if the writing process is interrupted. You need to assume that your thread may be interrupted at any point, so you need to either disable interrupts in delicate sections (with enterCriticalSection() and leaveCriticalSection() or cpsrCriticalSectionStart() and cpsrCriticalSectionEnd()) or make sure that writes and reads can only happen in an order that can’t cause issues.

The following libnds features are thread-safe:

  • Filesystem read/writes (DLDI, DSi SD and NAND, NitroFS).
  • Firmware read/writes.
  • libnds audio commands.
  • Maxmod and DSWiFi.
  • Standard C library functions like malloc() and fopen() (and variables like errno).
  • In general, anything that involves an ARM9 request to the ARM7 is thread-safe because the FIFO system has locks for each channel.
  • 2D sprite memory allocation code.

And the following aren’t:

  • videoGL (including the texture loading code).
  • Functions that use the divider and square root hardware accelerators.

Normally libnds only preempts threads when there’s an interrupt that some thread has enabled to do some real work. However, if you need threads to be interrupted more frequently, you can setup a hardware timer to cause time slicing with function cothread_setup_time_slicing(). In practice, this function sets up a timer to cause interrupts regularly, but it doesn’t setup a user handler. This means that the only thing the interrupt handler does is to save the current thread context and load the next thread context. This can be useful in a game that has multiple very CPU-heavy AI player thread, like a stragegy game with 2 or 3 CPU players. Your main thread can handle user input and rendering as usual, and the CPU players can run inside threads that have the same priority and that need to be preempted regularly so that they all get CPU time.

Many of the examples use cothread_setup_time_slicing() to make things harder for libnds and to test that frequent context switches work correctly.

Nested interrupts don’t cause threads to be preemted again. Only the top level interrupt handler will preempt the current thread and switch to a different one.

6. Thread priorities

Threads have a priority value which ranges from 127 (maximum priority, it runs before any other thread) and -128 (minimum priority, it only runs of no other threads are active). The main() thread starts with priority 0. Some system threads (like FIFO or WiFi handlers) have a higher priority, and some system threads (like the sleep thread) have a lower priority (all system threads are explained in a section further down in this chapter).

Setting the right priority to your threads is critical to optimize CPU usage. For example, if you are developing a game with an overworld section and you need to load assets asynchronously while moving around, you can have a main() thread that handles user input, rendering, queuing loads of assets… and a secondary thread with low priority that checks the queue of assets that need to be loaded and loads them to RAM. This way, the game logic will use as much CPU as it needs so that the player doesn’t notice any slowdown, and the asset loading code will only run if there isn’t anything more important to be done.

If you want to set the priority of a new thread right when it’s created, use cothread_create_priority() instead of cothread_create(). You can also call cothread_set_priority() later (it can change the priority of any thread, even the thread that is currently running), and you can get the priority of a thread with cothread_get_priority().

When you create a thread with cothread_create(), the new thread inherits the priority of the thread that created it.

Check this to see an example of using multiple thread priorities: examples/cothread/thread_priority.

As a final comment, thread priorities can be used in a way that can replace some interrupt handlers. For example, you can create a high-priority thread that always wait for a timer IRQ. When the timer IRQ happens, the current thread is preempted, and the next thread to run is the thread with the highest priority. If the highest priority thread is the timer handling thread, it will run before any other thread is allowed to run. The main advantage of this is that IRQ handlers are very limited in the things they can do (no malloc(), no printf(), no fread()) but high-priority threads are allowed to do anything you want.

For example, in libnds, messages received in the FIFO of each CPU are handled in a high-priority thread that yields for the “message received IRQ”. In DSWiFi, packets are handled in a thread that sleeps until a “WiFi event” interrupt happens.

7. Thread synchronization devices

There are two thread synchronization devices in libnds: mutexes and semaphores. Both of them are used to restrict access to resources used by multiple threads. Mutexes are used so that only one thread can access a shared resource, and semaphores can allow more than one thread to access the shared resource. Also, mutexes are slightly faster.

Both of them use cothread_yield_signal() and cothread_send_signal() internally so that a thread doesn’t have to waste CPU cycles while waiting for a mutex/semaphore to become available.

7.1 Mutex

A mutex can be “acquired” or “free”, so it’s used for resources that only one thread can access.

To use a mutex, create a comutex_t variable and initialize it with comutex_init(). Any thread that wants to acquire the mutex can use comutex_acquire(), which will mark the mutex as acquired (or make the thread sleep until the mutex is available). When you’re ready to release the mutex, call comutex_release().

comutex_acquire() locks the thread until the mutex is available. If you don’t want the thread to be locked until the mutex is released by other threads, you can use comutex_try_acquire(). This function tries to mark the mutex as acquired, but it simply returns false if it wasn’t possible and true if it succeeded.

Check this example to see how to have a producer thread and a consumer thread that use a mutex to access a common counter variable: examples/cothread/comutex.

7.2 Semaphore

A semaphore can be set to allow a specific number of threads to access a resource. In practice, it’s just a counter that increases whenever the semaphore is signalled by a thread and decrease when a thread waits and acquires the semaphore. If the counter value is 0, it can’t be acquired again.

To use a semaphore, create a cosema_t variable and initialize it with cosema_init(), which lets you define the initial value (the number of threads that can acquire it simultaneously).

When a thread wants to use the shared resource it needs to use cosema_wait(), which makes the thread sleep until it can be acquired. You can also use cosema_try_wait(), which works like in the case of mutexes. When a thread stops using the resource it has to call cosema_signal().

8. Allocating threads in DTCM and ITCM

Main RAM is much slower than DTCM and ITCM, so the stack of the main thread is placed in DTCM to increase performance of the application significantly. Threads created by the user can also have some resources allocated in DTCM and ITCM instead of main RAM to increase their performance.

Each thread owns three memory regions:

  • Thread context: Each thread is associated to a thread context struct. The struct has information such as the stack base and end, its priority and, when the thread is halted, the CPU state it had when it was paused. Generally, it’s a good idea to allocate this in DTCM to make context saves/restores faster.
  • Thread stack: All threads have their own stack. The stack is only used for that specific thread (interrupt handlers have their own stack) so you can adjust the stack size of each thread based on how much space they need. This is normally stored in DTCM as well.
  • Thread-local storage: All variables marked with tag __thread are allocated per-thread instead of once for the whole application. This is always allocated in main RAM, it can’t be allocated in DTCM or ITCM.

Whenever a thread is created the creation code needs to allocate the three specified regions. However, in some cases, it may be a better idea to allocate them statically (like in the case of the main and sleep threads). The memory allocated for a thread is released automatically when a detached thread ends. When a non-detached thread ends, cothread_delete() needs to be called to free the resources used by a thread.

The following flags can be used when creating a thread:

  • COTHREAD_CONTEXT_IN_DTCM and COTHREAD_CONTEXT_IN_ITCM: They tell cothread_create() to allocate the CPU context in DTCM or ITCM. Normally you want to allocate this in DTCM to maximize the context switch speed (the context of the main thread is stored in DTCM).

  • COTHREAD_STACK_IN_DTCM and COTHREAD_STACK_IN_ITCM: They tell cothread_create() to allocate the thread stack in DTCM or ITCM. Ideally you want to store the stack of your most active threads in DTCM (the stack of the main thread is stored in DTCM).

ITCM is generally an inferior choice. Very fast threads may want to run code from ITCM, and it isn’t possible to run code from ITCM and access data in ITCM as fast as running code from ITCM while accessing data in DTCM. However, if your code is in main RAM, and you don’t have enough space in DTCM for more threads, it may be a reasonable idea to allocate thread contexts and stacks in ITCM.

Check the following example to see all possible combinations of the flags: examples/cothread/stack_in_tcm.

9. System threads

All applications that use libnds are multithreaded applications (on both the ARM9 and ARM7) even if the developer doesn’t create any thread. This is a list of all current system threads:

  • Main thread: This is the thread that runs your application. It has priority 0 (neutral) and it’s the thread that calls main() at the beginning of your program. When this thread returns, the program ends.

  • FIFO handling thread: It handles messages received from the other CPU with the FIFO system and calls user handlers if they have been configured. Calling user handlers from a thread instead of from an IRQ handler allows the handlers to be much more complex and use utilities that require access to thread-local storage or locks (like malloc(), fopen(), fread(), printf()…). It has a priority higher than 0 so that FIFO messages are handled before returning to the main thread. If there are no FIFO messages to be handled, it sleeps.

  • Sleep thread: It’s a thread with the minimum possible priority (-128) that runs whenever all other threads are sleeping. This thread is in charge of:

    • Doing garbage collection of detached threads (and free their resources).
    • Halt the CPU to save power if there is nothing else to do.

    This thread needs to be active all the time so that the scheduling code always has at least one thread to jump to, even if all other threads are sleeping. For that reason, this thread uses cothread_yield() instead of other yield functions.

  • DSWiFi thread: In the ARM7 it runs the WiFi driver and handles the communications with the ARM9. In the ARM9 it handles communications with the ARM7 and it runs the lwIP library (which is the one that actually deals with protocols like TCP, UDP and IP).

If the threads of your application never yield for interrupts or events and the sleep thread is never run, the resources of detached threads that have finished will never be freed. If your application never sleeps, consider not using detached threads with a finite lifespan (it’s okay to have detached threads that never end).

10. Thread stacks

In order to create a thread you need to know its stack size so that it can be allocated in memory. If you pass 0 as stack size to cothread_create() it will use the default size (currently 1 KiB). This size is fairly arbitrary, and it may not be enough for what your thread needs to do, or it may be too much space that ends up being wasted.

Knowing how much stack space your code uses isn’t easy. You can use GCC option -fstack-usage (in CFLAGS), which will create .su files with the static stack usage of your code. However, if you call functions in libraries, you will also need to use this option when building the libraries. Even if you do all of this, it may not be trivial to determine the actual stack usage.

A more realistic option is to do it by trial and error. Debug builds of libnds add pre-determined values to the start and end of the stacks (canaries). They are checked whenever a thread stops running. If the value of the canaries has changed, it’s because a stack overflow (or underflow) has happened. You can try with different stack sizes until your code stops triggering stack overflows.

Remember that you can add LIBS := -lnds9d or LIBS := -lnds7d to your Makefiles to use debug builds of libnds.

User interrupt handler callbacks have their own independent stack, so you don’t need to consider interrupts when calculating stack usage in your threads. This lets you adjust the size of the thread stack to only what the thread needs to run its code. For example, if all your thread does is to increase a counter variable, you can assign it a 8 byte stack and it will work. However, if you use functions like fread(), you may need a bigger stack than the default size.

Debug builds of libnds also add canaries to the user IRQ stack, as we saw in the interrupts chapter. Remember that you can adjust the size of the system and user IRQ stacks by adding -Wl,--defsym,__irq_stack_size=1024 and -Wl,--defsym,__irq_user_stack_size=1024 to LDFLAGS in your Makefile.

Component CPU mode Stack location Stack size defined in
Global IRQ dispatcher IRQ DTCM __irq_stack_size
User IRQ callback Undefined DTCM __irq_user_stack_size
Thread System Selectable [1] cothread_create()

[1] Thread stacks can be placed in DTCM, ITCM or main RAM.