Thread Cancellation (pthread_cancel)

Source: Internet
Author: User
Tags mutex posix

Basic concepts
The Pthread_cancel call does not wait for the thread to terminate, it only requests. The thread will continue to run after the cancellation request (PTHREAD_CANCEL) is issued.
Until a cancellation point (Cancellationpoint) is reached. A cancel point is a location where the thread checks for cancellation and acts as requested.


Pthread functions related to thread cancellation
int Pthread_cancel (pthread_t thread)
Sends a terminating signal to thread, and returns 0 if successful, otherwise a value other than 0. Sending a success does not mean that thread will terminate.

int pthread_setcancelstate (int state, int *oldstate)
Set the response of this thread to the CANCEL signal, state has two values: pthread_cancel_enable (default) and Pthread_cancel_disable,
The signal is set to the cancled state and the cancel signal is ignored to continue running, if the old_state is not NULL then the original cancel state is saved for recovery.

int pthread_setcanceltype (int type, int *oldtype)
Sets the execution time for this thread to cancel the action, type is evaluated by two: Pthread_cancel_deffered and pthread_cancel_asychronous, only if the cancel state is enabled, The signal is received after continuing to run to the next cancellation point and then exit and immediately perform the Cancel action (exit); Oldtype if not NULL, the value of the canceled action type that is shipped.

void Pthread_testcancel (void)
is to say that Pthread_testcancel creates a cancellation point where it does not contain a cancellation point, but where it needs to be canceled, in order to respond to a cancellation request in an execution code thread that does not contain a cancellation point.
The Pthread_testcancel () function is valid when the thread cancellation feature is enabled and the cancellation state is set to a deferred state.
If Pthread_testcancel () is called when the Cancel function is disabled, the function does not work.
Be sure to insert pthread_testcancel () only in a sequence where thread-safe operation is canceled only. The Pthread standard also specifies several cancellation points in addition to the programmatically established cancellation point by calling Pthread_testcancel (). The test exit point is to test the cancel signal.


Cancel point:
The method of thread cancellation is to Cheng the cancel signal to the target line, but how to handle the cancel signal is determined by the target thread itself, either by ignoring, or immediately terminating, or continuing to Cancelation-point (the cancellation point), depending on the cancelation state.

The default processing that the thread receives the cancel signal (that is, the default state of the pthread_create () creation thread) is to continue running to the cancel point, which means to set a canceled state and the thread to continue running Exit only when running to Cancelation-point.

The Pthreads standard specifies several cancellation points, which include:
(1) Programmatically establish a thread cancellation point through the Pthread_testcancel call.
(2) The thread waits for a specific condition in pthread_cond_wait or pthread_cond_timewait ().
(3) The function that is blocked by sigwait (2)
(4) Some standard library calls. Typically, these calls include a thread that can be based on a blocking function.

By default, the cancellation feature is enabled. Sometimes, you may want the application to disable the cancellation feature. Disabling cancellation can result in delays in all cancellation requests,
Until the cancellation request is enabled again.
According to the POSIX standard, Pthread_join (), Pthread_testcancel (), pthread_cond_wait (), pthread_cond_timedwait (), sem_wait (), sigwait ( ) and other functions and
The system calls that cause blocking, such as read (), write (), are cancelation-point, and other pthread functions do not cause cancelation actions.
But Pthread_cancel's hand album claims that the C library function is not cancelation-point because the Linuxthread library does not combine well with the C library, but the cancel signal causes the thread to exit from the blocked system call and resets the EINTR error code , so you can call Pthread_testcancel () before and after a system call that needs to be cancelation-point, to achieve the targets required by the POSIX standard.
such as the following code snippet:
Pthread_testcancel ();
Retcode = Read (fd, buffer, length);
Pthread_testcancel ();

Attention:
Program design considerations, if the thread is in an infinite loop, and the loop body does not have the necessary path to the cancellation point, the thread cannot be terminated by a cancellation request from another external thread. Therefore, the Pthread_testcancel () call should be added to the required path on such a loop body.


Cancellation type (cancellation type)

We will find that the usual argument is that such a function is cancellation Points, and this method is easily confusing.
Because the execution of a function is a time process, not a point in time. In fact the real cancellation Points just in these functions cancellation Type is modified to phread_cancel_asynchronous and modified back to pthread_cancel_deferred Middle of a period of time.

There are two types of POSIX cancellation, one is delay cancellation (pthread_cancel_deferred), which is the default cancellation type for the system, which means that no real cancellation occurs until the thread reaches the cancellation point, and the other is an asynchronous cancellation (Phread_cancel_ asynchronous), when asynchronous cancellation is used, the thread can be canceled at any time.


Thread-Terminated cleanup work

There are two scenarios for POSIX thread termination: normal termination and abnormal termination.
A thread's active invocation of pthread_exit () or return from a thread function causes the thread to exit normally, which is a predictable exit method;
An abnormal termination is that the thread exits with the intervention of another thread, or because of an error in its own operation (such as access to an illegal address), which is not predictable.

Whether it is a predictable thread termination or abnormal termination, there will be a problem of resource release, without considering the exit due to running errors, how to ensure that the thread termination can smoothly release the resources they occupy, especially the lock resources, is a must be considered to solve the problem.
The most common scenario is the use of a resource exclusive lock: The thread locks it for access to the critical resource but is canceled by the outside during the access process, if the thread is in a response cancellation state, responds asynchronously, or there is a cancellation point on the run path before the exclusive lock is opened. The critical resource will never be released until it is locked. Outside cancellation is not predictable, so a mechanism is needed to simplify programming for resource release.

A pthread_cleanup_push ()/Pthread_cleanup_pop () function is provided in the POSIX threading API.
The terminating action in the program segment (including Call Pthread_exit () and cancellation point termination) that is used to automatically free resources-from the call point of Pthread_cleanup_push () to Pthread_cleanup_pop () will be executed Pthread_ The cleanup function specified by Cleanup_push ().

The API is defined as follows:
void Pthread_cleanup_push (void (*routine) (void *), void *arg)
void Pthread_cleanup_pop (int execute)

Pthread_cleanup_push ()/pthread_cleanup_pop () uses the first-in, post-out stack structure management, void routine (void *arg) function
When calling Pthread_cleanup_push (), the cleanup function stack is pressed, and multiple calls to Pthread_cleanup_push () will form a function chain in the cleanup function stack;
Termination action from the call point of the Pthread_cleanup_push to the program segment between Pthread_cleanup_pop (including call Pthread_exit () and exception termination, excluding return)
Will execute the cleanup function specified by Pthread_cleanup_push ().

When the function chain is executed, it pops up in the reverse order of the compression stack. Execute parameter indicates execution to Pthread_cleanup_pop ()
Whether the function is executed while the cleanup function is ejected, 0 means no execution, and not 0 for execution; This parameter does not affect the execution of cleanup functions at the end of an exception.

Pthread_cleanup_push ()/pthread_cleanup_pop () is implemented in a macro manner, which is a macro definition in Pthread.h:

#define Pthread_cleanup_push (Routine,arg) \ {struct _pthread_cleanup_buffer _buffer; \ _pthread_cleanup_push (&_ Buffer, (routine), (ARG)), #define PTHREAD_CLEANUP_POP (execute) \ _pthread_cleanup_pop (&_buffer, (execute)); }

Visible, Pthread_cleanup_push () has a "{", and Pthread_cleanup_pop () has a "}", so the two functions must appear in pairs and must be in a code snippet at the same level of the program to compile.

In the following example, when a thread terminates in a "do some work", Pthread_mutex_unlock (Mut) is invoked to complete the unlock action.

Pthread_cleanup_push (Pthread_mutex_unlock, (void*) &mut);p Thread_mutex_lock (&mut);/* Do some work */pthread_ Mutex_unlock (&mut);p thread_cleanup_pop (0), or void Cleanup (void *arg) {        pthread_mutex_unlock (&mutex);} void* thread0 (void* Arg) {        Pthread_cleanup_push (cleanup, NULL);//thread cleanup handler    p    thread_mutex_ Lock (&mutex);        Pthread_cond_wait (&cond, &mutex);        Pthread_mutex_unlock (&mutex);        Pthread_cleanup_pop (0);        Pthread_exit (NULL);}

Reference blog:
Cancel threads and cleanup work
Http://blog.sina.com.cn/s/blog_66fb0c830100y9hb.html

(thread-terminated cleanup work)
Http://www.cnblogs.com/mydomain/archive/2011/08/15/2139826.html

(a thread deadlock caused by a pthread_cancel)
Http://www.cnblogs.com/mydomain/archive/2011/08/15/2139830.html

Http://www.cnblogs.com/mydomain/archive/2011/08/15/2139850.html

Own Sina Blog (Java Multithreading related introduction)
Http://blog.sina.com.cn/s/blog_8da6362401013rcl.html

Thread Cancellation (pthread_cancel)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.