Page 1 of 1

Threads ... ?

Posted: Fri Apr 11, 2008 7:27 am
by White-spirit
Hello all,

I need to know what do I need to know to implement threads support for my OS in C or in ASM .

At this moment, malloc and free aren't implemented on my kernel, and I don't have a File System for my OS yet...

How to run two or more threads on the same time ? for example I want to run theses two threads : printf("Thread 1"); and printf("Thread 2"); .

Some links to very simple multi-tasking howto's would be nice .

The only thing I do understand yet is if there are two threads runing at the same time, the instructions sequence will be :

[1st instruction from Thread 1] Saving ESP, EIP ... and switching to Thread 2
[1st instruction from Thread 2] Saving ESP, EIP ... and switching to Thread 1
[2nd instruction from Thread 1] Saving ESP, EIP ... and switching to Thread 2
[2nd instruction from Thread 2] Saving ESP, EIP ... and switching to Thread 1
[3rd instruction from Thread 1] Saving ESP, EIP ... and switching to Thread 2
[3rd instruction from Thread 2] Saving ESP, EIP ... and switching to Thread 1

Thanks for help :) .

Posted: Fri Apr 11, 2008 7:38 am
by zerosum
I can't help you, but you may want to look at JamesM's tutorial:

http://jamesmolloy.co.uk/tutorial_html/ ... sking.html

Cheers,
Lee

Posted: Fri Apr 11, 2008 7:43 am
by AJ
Hi,

For a general overview, see Context Switching. In your example, you switch after every instruction, which would make for a very slow system. Generally, you will set up a time source (PIT? Local APIC Timer?) to cause an IRQ every, say, 10ms. The pseudo code is somthing like this:

Code: Select all

pusha   ;or 64 bit equivalent which will be a macro
push ds, es, fs and gs

mov eax, esp
push esp        ;for 32 bit GCC, this passes esp to the scheduler

call  scheduler

mov esp, eax ;for 32 bit GCC, this takes the scheduler return val (esp for incoming task)

pop gs, fs, es and ds
popa
iret
The fact that you are have already fired an IRQ means that EFLAGS, EIP and CS are already on the stack, and the IRET automatically pops the new values for these registers. Once this works for ring 0, you then need to worry about a TSS for ring3 -> ring 0 transitions.

Hope that helps get you started!

Cheers,
Adam

Posted: Sat Apr 12, 2008 5:31 am
by White-spirit
Thanks for the JamesM tutorial :)

So first of all, I'ill initialize an IDT, write my own malloc function and then I can switch between two threads with IRQs ( for example if the 10ms are past, the CPU will be forced to switch to another thread ) ? If it's only that, it's not very difficult :o .