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.
Related
I'm trying code multi threaded worker and job giver program
Job giver thread pushes jobs to array with random delayed data it can be processed 1 second later or 10000... second later all depends to job giver.
Worker thread nanosleep()s till get shortest delayed job, then process it and remove it from job array.
All works fine except if job giver pushes shorter delayed job to array and worker thread still nanosleep()s to old shortest job, so its get delayed more than expected.
For now as quick fix I made signal handler with signal() that handling SIGUSR1 signal.
When job giver pushes new shortest it sends SIGUSR1 to whole program and cancels worker's nanosleep().
But I don't think it's best way to do it since it sends to whole program and I just want to cancel one thread's nanosleep().
So in summary how I can cancel other thread's nanosleep() from main thread without touching signals?
Note; I'm using pthread on linux with C language.
Note; Delays are in nanoseconds. With current setup I'm able to hit 50µs loss.
You can possibly use pthread_kill() to deliver the SIGUSR1 to a single thread
From the manpage:
The pthread_kill() function sends the signal sig to thread, a thread in the same process as the caller. The signal is asynchronously directed to thread.
If sig is 0, then no signal is sent, but error checking is still performed.
This should only have an effect to the single thread you target.
You have a big XY problem here. Sleeping and signals are not the way to implement coordination between threads. I'd go so far as to say that sleeping in a multithreaded program is almost always indicative of some sort of bug.
The tool for what you are trying to do is Condition Variables. If you're not familiar with them, I'd highly recommend the Condition Variables part of this tutorial. Instead of sleeping, your workers should be doing a timed wait on the condition variable, called in a loop, and exiting from the loop when the condition they're waiting for is true.
Lets say we have two mutexes one is called x other one is y
x is used for general locking like don't try access in same time with multiple threads. pthread_mutex_lock and pthread_mutex_unlock
y is used for nanosleep. pthread_cond_wait, pthread_cond_timedwait and pthread_cond_signal
For suspend I use cond_wait y then resume with cond_signal y. If I need suspend for some time like nanosleep I use cond_timedwait y and resume it with same way cond_signal y.
Source:
stackoverflow.com/questions/59286893/canceling-nanosleep-from-another-thread#comment104779089_59286893
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?
}
I am working on a device driver, where i need to use sleep. I am using wait_event_interruptible() for sleeping. wait_event_interruptible() is not returning even condition becomes true. But when i close application with Ctrl+c, It is returning. That means it is caught signal. Why it is catching signal but not condition check ? Below is the code that i'm using in my driver.
/*Initialization of Wait queue*/
static DECLARE_WAIT_QUEUE_HEAD(my_queue);
/* Here i'm waiting for value at address becomes 1 when hardware writes data */
wait_event_interruptible(my_queue, *addr);
Suppose that the process that you have put to sleep is Process1. After the condition becomes true (1), some other process/thread needs to invoke wake_up on the waitqueue (my_queue) on which Process1 is waiting.
Then, Process1 that has went to sleep will wake up. After it has woken up, you should check for two cases immediately after your wait_event_interruptible() call:
Did the condition that you were waiting for happen?
OR, did a signal wake up Process1?
Detect which of these cases (if not both) occurred, and do the appropriate handling for them.
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.
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.