The developer of Pumpkin OS (which we talked about before), a port of the Palm OS to x86-64, has written a very interesting post about dealing with multi-threading. Pumpkin OS is multi-threaded from the start, but several parts of the operating system rely on old parts of Palm OS that were never meant to be multi-threaded – such as the M68K emulator used to run Palm OS applications written for that architecture.
The solution I came up with uses something called thread local storage. Each thread has access to a private memory region that the main thread can setup in advance. When a deeply nested function needs to access global state, instead of using a global variable, it gets a pointer to its local storage. Each emulated M68K thread writes to its own M68K state, not interfering with another thread. And no function prototype needs to change. The first step was to identify all global variables used by the M68K emulator, which were surprisingly few.
I’m so excited about this project.