Sleep a thread for an indefinite amount of time in Linux - c

I want to make a thread sleep for an indefinite amount of time. The reason I want to do this is because my program only takes action when it receives a signal and has nothing to do in the primary thread. Therefore, all processing is done inside the signal handler. How can I sleep for an indefinite amount of time?

I believe you're looking for the pause function:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/pause.html
You could do something like: for (;;) pause();

If you're just doing something on another thread, simply call pthread_join on that thread and it will pretty much block "forever". You could achieve the same effect using a condition variable.

Use semaphores!
Have your thread blocked on a semaphore by using sem_wait. Once you need to wake your thread signal the semaphore by using sem_post from another thread.

POSIX provides the sigsuspend function to wait for a signal. (As mentioned in another answer, pause works as well.)

Related

Canceling nanosleep() from another thread

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

Is there any possibility to pause a thread from inside self thread and resume it back after passing a signal from other thread in C Programming?

Problem: Invoke a thread, which by default will be paused. It should resume after passing a signal from other thread, and perform the task.
Semaphore and pthread condition i had already tried and they are taking lot of time, if i have to pass condition signal very fast in a loop. Is there any other way? or any way to pause/resume a thread in C Programming?
Operating System: Linux
You can use select/poll/epoll and wait with it on signalfd.

Sending signal to pthread to abort sleeping

I'm have a pthread function, which sleeps most of the time using usleep()
I would like to send a signal from the main process to the thread to interrupt the sleeping sometimes.
The problem is that I can't find any reference of which signal exactly to send using pthread_kill()
the usleep() man page, states that SIGALRM should not be used together with usleep()
Do I need to use a specific signal, it doesn't matter ?
The tools to synchronize between threads are not signals and usleep (or nanosleep) but combinations of pthread_mutex_t and pthread_cond_t. Just have your thread wait on a condition (this can be done with a timeout) and have your main thread send a "signal" on the condition variable.
usleep returns with EINTR on every signal that's delivered to a thread/process. You'll probably be best off using SIGUSR signals.
Also, usleep is now obsolete : consider using nanosleep instead. As an added bonus, you'll know how much sleep time was remaining at the time of the delivery of the signal.

Linux: Whether calling wait() from one thread will cause all other threads also to go to sleep?

"The wait() system call suspends execution of the current process until one of its children terminates" . Waitpid also is similar.
My Question is whether calling wait() from one thread will cause all other threads (in the same process) also to go to sleep ? Do the behavior is same for detached threads also?
This is just a bug in the manual. wait suspends the calling thread, not the process. There is absolutely no way to suspend the whole process short of sending it SIGSTOP or manually suspending each thread one at a time.
As far as I know, calling wait from any thread will cause all threads which are associated with that process to halt.
But don't hold me to that. Best thing to do would be to test it.
Should only stop the current thread. If you want to make people ill when they look at your code and cause yourself a lot of problems you can use this for jury rigged thread synchronization. I wouldn't reccommend it though.

Kill Thread in Pthread Library

I use pthread_create(&thread1, &attrs, //... , //...); and need if some condition occured need to kill this thread how to kill this ?
First store the thread id
pthread_create(&thr, ...)
then later call
pthread_cancel(thr)
However, this not a recommended programming practice! It's better to use an inter-thread communication mechanism like semaphores or messages to communicate to the thread that it should stop execution.
Note that pthread_kill(...) does not actually terminate the receiving thread, but instead delivers a signal to it, and it depends on the signal and signal handlers what happens.
There are two approaches to this problem.
Use a signal: The thread installs a signal handler using sigaction() which sets a flag, and the thread periodically checks the flag to see whether it must terminate. When the thread must terminate, issue the signal to it using pthread_kill() and wait for its termination with pthread_join(). This approach requires pre-synchronization between the parent thread and the child thread, to guarantee that the child thread has already installed the signal handler before it is able to handle the termination signal;
Use a cancellation point: The thread terminates whenever a cancellation function is executed. When the thread must terminate, execute pthread_cancel() and wait for its termination with pthread_join(). This approach requires detailed usage of pthread_cleanup_push() and pthread_cleanup_pop() to avoid resource leakage. These last two calls might mess with the lexical scope of the code (since they may be macros yielding { and } tokens) and are very difficult to maintain properly.
(Note that if you have already detached the thread using pthread_detach(), you cannot join it again using pthread_join().)
Both approaches can be very tricky, but either might be specially useful in a given situation.
I agree with Antti, better practice would be to implement some checkpoint(s) where the thread checks if it should terminate. These checkpoints can be implemented in a number of ways e.g.: a shared variable with lock or an event that the thread checks if it is set (the thread can opt to wait zero time).
Take a look at the pthread_kill() function.
pthread_exit(0)
This will kill the thread.

Resources