Thread sleeping

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
nexos
Member
Member
Posts: 1081
Joined: Tue Feb 18, 2020 3:29 pm
Libera.chat IRC: nexos

Thread sleeping

Post 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
"How did you do this?"
"It's very simple — you read the protocol and write the code." - Bill Joy
Projects: NexNix | libnex | nnpkg
User avatar
AndrewAPrice
Member
Member
Posts: 2300
Joined: Mon Jun 05, 2006 11:00 pm
Location: USA (and Australia)

Re: Thread sleeping

Post 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.)
My OS is Perception.
thewrongchristian
Member
Member
Posts: 426
Joined: Tue Apr 03, 2018 2:44 am

Re: Thread sleeping

Post 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.
nexos
Member
Member
Posts: 1081
Joined: Tue Feb 18, 2020 3:29 pm
Libera.chat IRC: nexos

Re: Thread sleeping

Post 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!
"How did you do this?"
"It's very simple — you read the protocol and write the code." - Bill Joy
Projects: NexNix | libnex | nnpkg
Post Reply