Search code examples
cmultithreadingpowerpc

Threading Implementation


I wanted to know how to implement my own threading library.
What I have is a CPU (PowerPC architecture) and the C Standard Library.

Is there an open source light-weight implementation I can look at?


Solution

  • At its very simplest a thread will need:

    1. Some memory for stack space
    2. Somewhere to store its context (ie. register contents, program counter, stack pointer, etc.)

    On top of that you will need to implement a simple "kernel" that will be responsible for the thread switching. And if you're trying to implement pre-emptive threading then you'll also need a periodic source of interrupts. eg. a timer. In this case you can execute your thread switching code in the timer interrupt.

    Take a look at the setjmp()/longjmp() routines, and the corresponding jmp_buf structure. This will give you easy access to the stack pointer so that you can assign your own stack space, and will give you a simple way of capturing all of the register contents to provide your thread's context.

    Typically the longjmp() function is a wrapper for a return from interrupt instruction, which fits very nicely with having thread scheduling functionality in the timer interrupt. You will need to check the implementation of longjmp() and jmp_buf for your platform though.

    Try looking for thread implementations on smaller microprocessors, which typically don't have OS's. eg. Atmel AVR, or Microchip PIC. For example : discussion on AVRFreaks