how to cancel (not terminate) boost thread? - multithreading

I like C# CancellationTokenSource which allows me to terminate the Task as shown in this article.
What would be the similar algorithm of canceling boost::thread? I don't want to "kill" or "terminate" the thread. Instead i want to "request" the task to finish. Then i need to wait until the task is finished.

You can use the boost thread interruption
A running thread can be interrupted by invoking the interrupt() member
function of the corresponding boost::thread object. When the
interrupted thread next executes one of the specified interruption
points (or if it is currently blocked whilst executing one) with
interruption enabled, then a boost::thread_interrupted exception will
be thrown in the interrupted thread. If not caught, this will cause
the execution of the interrupted thread to terminate. As with any
other exception, the stack will be unwound, and destructors for
objects of automatic storage duration will be executed.

Related

Why does a single thread exception crash entire program (how to prevent this?)

If I run, for example,
int x = *(0x00000);
The program crashes. But why does the whole program crash instead of that single thread? I created multiple threads that just sleep continuously to test this out. Is there any way to make only the current thread exit, not the whole program (on windows using winapi)?
Thanks.
But why does the whole program crash instead of that single thread?
This is by design. If nobody (not the debugger if attached and not the process itself) handles the user mode exception, the system terminates the process, and this is logical.
All resources are shared per process, not per thread. After an unhandled exception happens the process is probably in an unstable/corrupted state. New exceptions will occur or the other threads might hang.
The thread could for example own some critical section or another resource at the time of the exception. If the thread terminates at this point the resource will be always in use by the crashed thread. When another thread tries to enter this "critical section" (in a broad sense) it hangs forever. (For example a heap critical section).
So better just terminate the process instead of getting new exceptions and undefined behavior in the process.
By the same line of reasoning, if an unhandled exception was in kernel mode the system terminates itself and tries to create a BSOD. Because after an unhandled exception in the kernel, all systems are in an unstable state and simply terminating the buggy thread is not a solution.
Is there any way to make only the current thread exit, not the whole
program (on windows using winapi)?
Formally yes, it's easy, you can set UnhandledExceptionFilter with the SetUnhandledExceptionFilter function and inside UnhandledExceptionFilter simply call TerminateThread for the current thread ( GetCurrentThread() ) because
The exception handler specified by lpTopLevelExceptionFilter is
executed in the context of the thread that caused the fault.
Also note that this callback is called only if the process is not being debugged.
However, terminating the thread is not a proper solution. The solution is that there must not be exceptions in your process or you need to handle it. If you can not the process must end.

Do I need to check for my threads exiting?

I have an embedded application, running as a single process on Linux.
I use sigaction() to catch problems, such as segmentation fault, etc.
The process has a few threads, all of which, like the app, should run forever.
My question is whether (and how) I should detect if one of the threads dies.
Would a seg fault in a thread be caught by the application’s sigaction() handler?
I was thinking of using pthread_cleanup_push/pop, but this page says “If any thread within a process calls exit, _Exit, or _exit, then the entire process terminates”, so I wonder if a thread dying would be caught at the process level …
It is not a must that you need to check whether the child thread is completed.
If you have a need of doing something after the child thread completes its processing you can call thread_join() from the main thread, so that it will wait till the child threads completes execution and you can do the rest after this. If you are using thread_exit in the main thread it will get terminated once it is done, leaving the spawned threads to continue execution. The process will get killed only after all the threads completes execution.
If you want to check the status of the spawned threads you can use a flag to detect whether it is running or not. Check this link for more details
How do you query a pthread to see if it is still running?

How to gracefully exit a thread?

I am trying to assign a routine to the posix thread. When it is completing the routine, the calling thread is not exiting. Every time, I am creating a new thread and assigning a same routine to the new thread in while loop. New thread is created only for 379 times, after that thread creation is failed with status 11 means PTHREAD_MAX_LIMIT has been reached. Although in the calling thread I am using the pthread_exit(NULL).
I think you need to create your threads in the "detached" mode, otherwise you need to "join" them with the main thread (the one that creates the threads).
See this tutorial for details.

Interrupt while placing process on the waiting queue

Suppose there is a process that is trying to enter the critical region but since it is occupied by some other process, the current process has to wait for it. So, at the time when the process is getting added to the waiting queue of the semaphore, suppose an interrupt comes (ex- battery finished), then what will happen to that process and the waiting queue?
I think that since the battery has finished so this interrupt will have the highest priority and so the context of the process which was placing the process on the waiting queue would be saved and interrupt service routine for this routing will be executed.
And then it will return to the process that was placing the process on the queue.
Please give some hints/suggestions for this question.
This is very hardware / OS dependant, however a few thoughts:
As has been mentioned in the comments, a ‘battery finished’ interrupt may be considered as a special case, simply because the machine may turn off without taking any action, in which case the processes + queue will disappear. In general however, assuming a non-fatal interrupt and an OS that suspends / resumes correctly, I think it’s unlikely there will be any noticeable impact to the execution of either process.
In a multi-core setup, the process may not be immediately suspended. The interrupt could be handled by a different core and neither of the processes you’ve mentioned would be any the wiser.
In a pre-emptive multitasking OS there's also no guarantee that the process adding to the queue would be resumed immediately after the interrupt, the scheduler could decide to activate the process currently in the critical section or another process entirely. What would happen when the process adding itself to the semaphore wait queue resumed would depend on how far through adding it was, how the queue has been implemented and what state the semaphore was in. It may be that it never gets on to the wait queue because it detects that the other process has already woken up and left the critical section, or it may be that it completes adding itself to the queue and suspends as if nothing had happened…
In a single core/processor machine with a cooperative multitasking OS, I think the scenario you’ve described in your question is quite likely, with the executing process being suspended to handle the interrupt and then resumed afterwards until it finished adding itself to the queue and yielded.
It depends on the implementation, but conceptually the same operating process should be performing both the addition of the process to the wait queue and the management of the interrupts, so your process being moved to wait would instead be treated as interrupted from the wait queue.
For Java, see the API for Thread.interrupt()
Interrupts this thread.
Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.
If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.
If none of the previous conditions hold then this thread's interrupt status will be set.
Interrupting a thread that is not alive need not have any effect.

Interrupt Thread

Can any body tell what is the purpose of using interrupt method of thread. Why we call interrupt method during execution??
Thanks
You call the interrupt method to interrupt the thread if it's in a blocking state... usually you interrupt a thread that's in a blocking state because it's either taking too long or your system is shutting down and you want to cancel whatever that thread is doing. Interrupt offers a "graceful" way to terminate a blocking thread, because it raises an interrupt exception and it's presumed that your thread is handing that exception. When your thread gets the interrupt exception, then it should gracefully terminate (i.e. clean up the state and exit any loops).
P.S. What programming language are you using?

Resources