Take the 2-minute tour ×

I'm curious to know how one would code concurrent software on Intel x86 assembly. Both threads or coroutines with yielding are interesting.

I realize this isn't practical to do in assembly, but I'm just curious.

share|improve this question
add comment

3 Answers

up vote 4 down vote accepted

If you're talking about user space, the same way you do it in e.g. C. That is, you call pthread_create() (or whatever is the "create new thread" API on your OS) with appropriate arguments (including the address of the new thread's "main" function) and off you go.

If you're talking about bare-bones level without an OS to help you, then you'll allocate a block of memory (from the memory allocator you previously wrote) for the stack of your new thread, setup a periodic timer tick which runs (your previously written) scheduler code which saves register contents and switches between your thread stacks, etc.

As to how to do it with ASM instead of C? Well, except for a lot more sweat and tears, basically the same.

share|improve this answer
Regarding that second part (without an OS to help), what kind of asm instructions would you have to use to run some code on different cores? I realize I can do e.g. time-based slicing and preempt my own threads to achieve basic multitasking, but what about real physical cores where they actually run code simultaneously. How does that work? I guess I am asking how an OS does multithreading for multicore CPUs in general terms. –  Tower Sep 5 '11 at 13:19
In principle it's simple, you just set the IP (instruction pointer) register of the CPU to where you want it to start running. In practice, starting up all the cores is massively complicated (e.g. how to set up interrupts), and there is a spec for it: intel.com/design/pentium/datashts/242016.htm . –  janneb Sep 5 '11 at 13:34
add comment

On X86 processors, multiprocessor (and multithread) communication is done through the APIC (advanced programmable interrupt controllers) http://en.wikipedia.org/wiki/Intel_APIC_Architecture .

When the OS starts, only one logical processor is running OS code, to confirm to legacy single processor behavior.

The OS uses the APIC to send a "SIPI" (Startup Inter-Processor Interrupt) to every other thread.
Each thread wakes up, and updates a memory region so the main thread knows how many processors it has to work with.
After each thread announces itself, it goes to a low power, interruptible state.

WHen the OS wants to run something on that logical processor, it has the currently running processor send an IPI (InterProcessor Interrupt) via the APIC.
When the task is done, the logical processor can go back to the low-power state, waiting for the next interrupt.

share|improve this answer
add comment

Well, you wouldn't really want to, but you could use spinlocks: http://en.wikipedia.org/wiki/Spinlock

share|improve this answer
add comment

Your Answer


