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
Thread sleeping
- AndrewAPrice
- Member
- Posts: 2300
- Joined: Mon Jun 05, 2006 11:00 pm
- Location: USA (and Australia)
Re: Thread sleeping
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.)
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.)
My OS is Perception.
-
- Member
- Posts: 426
- Joined: Tue Apr 03, 2018 2:44 am
Re: Thread sleeping
I use condition variables in general.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
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
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!