Page 1 of 1
Thread sleeping
Posted: Tue May 19, 2020 10:29 am
by nexos
Hello,
I am trying to make a thread sleeping system. It will work with timer and IO. I was wondering what the best way to make it is.
Thank you for your help
Re: Thread sleeping
Posted: Tue May 19, 2020 11:38 am
by AndrewAPrice
A simple solution:
Have a linked list of awake threads. Each time the scheduler is called, enter the next thread on this list.
When threads go to 'sleep', remove them from this linked list.
To wake a thread up, add it back to this linked list.
Somewhere in your thread object, have a boolean if the thread is awake/asleep so you don't add to the link list twice.
IO is a little more complicated. You could send messages to threads and have a "Get Next Message" function that sleeps if there are no messages. (And the sender will wake it if it's sleeping for a message.)
Re: Thread sleeping
Posted: Wed May 20, 2020 5:06 pm
by thewrongchristian
nexos wrote:Hello,
I am trying to make a thread sleeping system. It will work with timer and IO. I was wondering what the best way to make it is.
Thank you for your help
I use condition variables in general.
Then your interrupt handler signals the condition variable, it'll wake up your thread that is waiting for the interrupt.
So long as your condition variable and mutex are properly implemented, you should never lose any interrupt signals, and will be a good test of your synchronization primitives to ensure they work in an interrupt environment.
My timer is a bit simpler, using just a spinlock to protect timer structures and running callbacks in the interrupt context. But even there, for a thread sleep, I still use a condition variable to communicate between the timer callback and the thread that is sleeping. That way, you can also interrupt the sleep by signalling the condition variable early before the timer expires.
Re: Thread sleeping
Posted: Thu May 21, 2020 1:50 pm
by nexos
I just finished it. It uses a event system, which is somewhat modeled after Windows's WaitForSingleObject. You can find it at
https://github.com/NexSuite/NexNix/blob ... oc/event.c. Thank you all for your help!