Sleep function call leads to which scheduler state? - c

I have a question with regard to the sleep function declared in unistd.h
Assume we use a CFS scheduler.
We have a process that is ready to run(lets call this "READY" state),it gets picked to run,and now is running(so called "RUNNING" state).
During its execution in the RUNNING state it encounters a sleep statement,say sleep(10) that makes it sleep for 10 seconds or until a signal gets delivered or whichever is sooner.
Now when sleep(10) is being executed,is the process in READY state or is it put back into its original priority in the RUNNING queue or is it put to the WAIT queue.
I am unable to visualize the correct sequence of events.One thought process suggests that it remains in the READY queue,while another thought is that its put to the WAIT queue waiting for a timer expiry of some sorts.
Please let me know how this would work,or if there is something wrong in my question. Thanks

I believe it depends on the duration of the sleep, i.e., if the wait is busy then it can be running, if the wait is long then it will be in the wait queue. Also, you should be able to confirm this by putting a process to a long sleep and checking its state.

Related

Stopping a pthread which is in sleep

I have a thread (This is a Pthread in C implementation) which reads a value from a file every 5 secs. During shutdown, this causes an issue where the shutdown process wants to delete the thread but since it's sleeping, it has to wait for 5 secs for the sleep
to be done and then delete. How can I stop the thread even if it's in sleep as soon as I get the shutdown signal?
I already have a condition variable where the thread sleeps only if the condition is true (i.e - thread is running).
Scenario - As soon as the thread entered sleep, the shutdown signal is received; we have no way to proceed but to wait for the sleep to be completed.
Let's say
if (isThreadRunning == true)
{
sleep(5)
}
As soon as the shutdown signal is received the condition variable is made to be false. But even in this case, there is a chance that the signal might come just after 1st second we need to wait for 4 more seconds
The use of condition variable …
How can I stop the thread even if it's in sleep as soon as I get the shutdown signal?
There are a few ways to handle this.
Does this thread actually need be joined?
If not, simply call exit in the main thread, and this thread will disappear into the void.
The problem with this approach is that there might be some necessary cleanups which this thread must perform.
Instead of calling sleep(5), use pthread_cond_timedwait, with the condition of "thread should continue running".
When the pthread_cond_timedwait returns, check the condition. If true, read the number from the file and go back to pthread_cond_timedwait. If false, return from the thread function.
The main thread should signal the condition and then join the thread.
Note that spurious wakeups are possible, and so you should also check whether 5s have passed since the last time you've read the file.
Instead of sleep(5), use usleep(1000). When usleep returns, first check whether you should keep running, and if so, whether 5s have elapsed since last time your read the file.
This solution is a kind of "busy wait" -- the thread will wake up much more than necessary.
But it's simple and bounds the longest delay on shutdown to 1ms.

Correct way to unblock a kernel thread

There are linux kernel threads that do some work every now and then, then either go to sleep or block on a semaphore. They can be in this state for several seconds - quite a long time for a thread.
If threads need to be stopped for some reason, at least if unloading the driver they belong to, I am looking for a way to get them out of sleep or out of the semaphore without waiting the whole sleep time or triggering the semaphore as often as required.
I found and read a lot about this but there are multiple advises and I am still not sure how things work. So if you could shed some light on that.
msleep_interruptible
What is able to interrupt that?
down_interruptible
This semaphore function implies interrupt-ability. Same here, what can interrupt this semaphore?
kthread_stop
It's described as sets kthread_should_stop to true and wakes it... but this function blocks until the sleep time is over (even if using msleep_interruptible) or the semaphore is triggered.
What am I understanding wrong?
Use a signal to unblock - really?
My search found a signal can interrupt the thread. Other hits say a signal is not the best way to operate on threads.
If a signal is the best choice - which signal do I use to unblock the thread but not mess it up too much?
SIGINT is a termination signal - I don't intend to terminate something, just make it go on.
More information
The threads run a loop that checks a termination flag, does some work and then block in a sleep or a semaphore. They are used for
Situation 1.
A producer-consumer scenario that uses semaphores to synchronize producer and consumer. They work perfectly to make threads wait for work and start running on setting the semaphore.
Currently I'm setting a termination flag, then setting the semaphore up. This unblocks the thread which then checks the flag and terminates. This isn't my major problem. Hovever of course I'd like to know about a better way.
Code sample
while (keep_running) {
do_your_work();
down_interruptible(&mysemaphore); // Intention: break out of this
}
Situation 2.
A thread that periodically logs things. This thread sleeps some seconds between doing it's work. After setting the flag this thread terminates at it's next run but this can take several seconds. I want to break the sleep if necessary.
Code sample
while (keep_running) {
do_your_work();
msleep(15000); // Intention: break out of this - msleep_interruptible?
}

Get ThreadState of suspended thread

For a simple sampling profiler I'm suspending a target thread, get its current stacktrace, then continue it.
Now I would like to highlight a sample differently if the thread was in a waiting state.
So I want to know if the thread was blocking (waiting via WaitForSingleObject, pausing via Sleep, ...) at the time it was suspended.
I can get this information via NtQuerySystemInformation(SystemProcessInformation), but that gets much more than needed, the information of each thread of each process.
Also I saw Performance Counters, but I'm not sure if it's possible with this API, if I only have the thread ID/handle.
UPDATE:
IInspectable gave me a hint with Wait Chain Traversal, while it seemed a good fit, it gives back the status ObjectStatus==WctStatusBlocked for all suspended threads, which isn't unreasonable, but doesn't work for my problem. It is also very slow, I assume because it collects the data for the whole chain, while I only care for the first element.
While not exactly what I wanted, QueryThreadCycleTime is close enough.
So each time the thread is suspended, QueryThreadCycleTime is called, which returns the number of CPU clock cycles used by this thread up to this point.
If the difference to the previous call is below a certain limit, the current sample is then considered as waiting.
It's not perfect, the first sample taken while the thread entered a waiting state is not detected as waiting, and the limit might not work for all CPUs the same.

Non blocking wait for child processes to exit

I have a program in C that launches 100 child processes with fork() and then waits for them to fininsh using a wait in a loop. I would like to wait a maximum amount of time for them all to finish, so the parent process doesn't stay blocked if one of them is, and if that time is over, kill the unfinished ones.
Which would be the best way to do that?
Set an alarm for the desired time. If the alarm fires, kill whichever of the list of children you original had have not yet died, and send them appropriate 'go away' signals.
I recommend sending SIGTERM or SIGHUP first; then collect the bodies. If there are any left over after another short delay, then send the SIGKILL signal. If you get too dramatic (SIGKILL) too quickly, the programs do not get an opportunity to clean up any mess they've made.
The child processes need to signal that they are finished to the main process in some way (you can have them pass a message back to the main process, have them create a file stating that they are finished, or whatever other way is easiest for you). Once that mechanism is in place, have the main process check for the signal that the processes have finished, if it has received them all then continue on, otherwise wait some amount of time before checking again. In this loop add a check to see if you max timeout has been reached, and if so then continue.

Pthread - What is the difference between time.h::sleep() and pthread.h::pthread_yield()?

I spent a good long while looking for info on the differences between time.h::sleep() and pthread.h::pthread_yield() but was unable to find any solid reference material and so I am posting this question.
What is the difference between time.h::sleep() and pthread.h::pthread_yield()?
Update:
The reason I ask is because I was using sleep() to sleep() each individual thread... and my application started having issues when there was 8 threads vs 4 threads. When I went online to see if sleep() only affects each thread, I couldn't find any good reference stating whether Sleep() affects the entire process OR sleep() only affects the individual thread.
From pthread_yield:
The pthread_yield subroutine forces the calling thread to relinquish use of its processor, and to wait in the run queue before it is scheduled again. If the run queue is empty when the pthread_yield subroutine is called, the calling thread is immediately rescheduled.
From the sleep manpage:
sleep() makes the calling process sleep until seconds seconds have elapsed or a signal arrives which is not ignored.
If you don't want to have a real time delay in your threads and just want to allow other threads to do their work, then pthread_yield is better suited than sleep.
sleep() causes your program to stop executing for a certain length of time. No matter what else happens on the system, your thread will not start again until at least the length of time passed to sleep() has elapsed. pthread_yield() notifies the operating system that your thread is done working, and that it can switch execution to another thread. However, if there is no higher-priority thread that needs to do work at that time, your thread may start again immediately.
IOWs, after sleep() your thread is guaranteed to stop running even if no one else needs to run, while pthread_yield() is just a polite way to give other threads a chance to run if they need to.
Update in response to question update: both sleep() and pthread_yield() affect only the calling thread.
sleep(s) takes the current thread of execution and suspends it until s seconds have passed (or it is woken up by a signal.)
In more practical terms, when you call sleep(), that thread will cease execution and just... wait until the specified time has passed. Once it passes, that thread is placed into the ready queue.
pthread_yield() says "take this thread, and put it into the ready queue." Your thread will stop execution and be in the 'waiting' state to be selected/run by the scheduler. This does not gaurantee that your thread will not immediately resume running. But it gives another thread a chance to run at a given point in its execution.
I am going to go out on a limb and say that sleep(0) would accomplish the same thing as a pthread_yield() - both stopping execution and placing the thread in the ready queue.

Resources