
But the approach is feasible and rather elegant if used properly.
PTHREAD C RETURN INSTALL
After the threads are created, you restore the mask and install a handler.Ĭancellation points can be tricky if the threads allocates a lot of resources in that case, you will have to use pthread_cleanup_push() and pthread_cleanup_pop(), which are a mess. You do so before spawning the threads to avoid having them doing it by themselves and needing to synchronize with the parent. The need for blocking/unblocking signals is that if you send SIGINT to the process, any thread may be able to catch it. Pthread_sigmask(SIG_SETMASK, &oldset, NULL) threadreturn: It is the parameter that acts as a pointer to the particular location where we have defined the exit. Parameters for pthreadjoin: The parameter used here are: threadid: It is the ID of the thread for which the thread in line waits.

Restore the old signal mask only for this thread. pthreadjoin: This is a function used at the time of wait for the termination of the thread. Install the signal handler for SIGINT. Pthread_create(&thread1, NULL, thread, &(unsigned int)) Pthread_sigmask(SIG_BLOCK, &sigset, &oldset) This will avoid them catching SIGINT instead of this thread. The threads will inherit the signal mask. The pthreadmutextrylock () function shall be equivalent to pthreadmutexlock (), except that if the mutex object referenced by mutex is currently locked (by any thread, including the current thread), the call shall return immediately. sleep() is a cancellation point in this example. Attempting to unlock the mutex if it is not locked results in undefined behavior. Printf("Thread %u running.n", *(unsigned int*)argument) The error-checking has been omitted for clarity. In your case, it seems a good opportunity to use cancellation points. Refer to Kill Thread in Pthread Library for more details. The last parameter of pthreadcreate () is passed. It must take a single void parameter and return a single void value. The pthreadcreate () imposes a strict format on the prototype of the function that will run in the new thread. Have the threads install a signal handler which provides a mechanism for termination (setting a flag and reacting to EINTR).īoth approaches has caveats. Thread Arguments and Return Values Computer Systems Fundamentals.
.jpg)
The thread will terminate when requested to cancel and it reaches a cancellation point, thus ending execution in a controlled fashion There are mainly two approaches for thread termination.
