Canceling threads in Pthread

Source: Internet
Author: User
Tags posix

Cancel Thread

The cancel operation allows a thread to request that any other thread in its process be terminated. When you do not want or need to perform further operations on a group of related threads, you can choose to perform a cancel operation.

An example of canceling a thread is asynchronously generating a cancellation condition, such as a user request to close or exit a running application. Another example is the completion of tasks performed by many threads. One of these threads may eventually finish the task, while the other threads continue to run. Because the running thread is not useful at this time, these threads should be canceled.

Cancel Point

The thread should be canceled only if the operation is safe to cancel. The pthreads standard specifies several cancellation points, which include:

    • The thread cancellation point is programmatically established through the pthread_testcancel call.

    • The thread waits for a specific condition in pthread_cond_wait or pthread_cond_timedwait (3C) to appear.

    • The thread that was blocked by sigwait (2) .

    • Some standard library calls. Typically, these calls include functions that a thread can base its blocking on. For a list, see the cancellation (5) man page.

The cancellation feature is enabled by default. Sometimes, you may want the application to disable the cancellation feature. Disabling the Cancel feature causes all cancellation requests to be deferred until the cancellation request is enabled again.

For information about disabling the cancellation feature, see pthread_setcancelstate syntax

Place a cancellation point

There is a risk of performing a cancel operation. most of the dangers are related to fully recovering invariants and freeing shared resources . Be careful when you cancel a thread, or you might leave the mutex locked and cause a deadlock. Alternatively, the canceled thread may retain the allocated memory area, but the system cannot recognize this part of the memory and cannot release it.

The standard C library specifies that a cancellation interface is used to programmatically allow or suppress the cancellation of functionality. The cancellation point defined by the library is a set of points that may perform cancellation operations. The library also allows you to define the scope of the cancellation handler to ensure that those handlers run at the expected time and location. The cleanup service provided by the cancellation handler can restore resources and state to a state that is consistent with the starting point.

You must have a certain understanding of the application before you can place the cancellation point and execute the cancellation handler. mutual exclusion is certainly not a point of cancellation and should only be kept as short as necessary.

Limit the asynchronous cancellation zone to a sequence that has no external dependencies, because external dependencies can result in suspended resources or unresolved state conditions. When returning from an alternate nested cancellation state, be careful to restore the cancellation state. This interface provides functionality for ease of recovery:pthread_setcancelstate (3C) preserves the current cancellation state in the referenced variable,pthread_setcanceltype (3C) Preserves the current cancellation type in the same way.

The cancel operation may be performed in the following three different scenarios:

    • Asynchronous

    • Perform various points defined by criteria in a sequence

    • pthread_testcancel()when called

By default, the cancel operation is performed only at a point that is reliably defined by the POSIX standard.

Whenever you need to be aware that resources and states have been restored to the same state as the starting point

pthread_setcancelstate Syntax
state, int * oldstate );
oldstateret;/* enabled * ret = Pthread_setcancelstate (pthread_cancel_enable, & oldstate );/* disabled */ ret = Pthread_ Setcancelstate (pthread_cancel_disable, & oldstate );
pthread_setcancelstate return value

pthread_setcancelstate()Returns zero after a successful completion. Any other return value indicates an error occurred. The pthread_setcancelstate() function fails and returns the corresponding value if the following conditions occur

EINVAL

Describe:

The state is not pthread_cancel_enable or pthread_cancel_disable.

pthread_setcanceltype Syntax
type, int * oldtype );
oldtyperet;/* Deferred mode * ret /= Pthread_setcanceltype (pthread_cancel_deferred, & oldtype );/* Async mode*/ ret = Pthread_ Setcanceltype (pthread_cancel_asynchronous, & oldtype );

When you create a thread, the cancellation type is set to delay mode by default. In deferred mode, the thread can only be canceled at the cancel point. In asynchronous mode, you can cancel a thread at any point during execution. Therefore, it is not recommended to use asynchronous mode.

pthread_setcanceltype return value

pthread_setcanceltype()Returns zero after a successful completion. Any other return value indicates an error occurred. The function fails and returns the corresponding value if the following conditions occur.

EINVAL

Describe:

The type is not pthread_cancel_deferred or pthread_cancel_asynchronous.

pthread_testcancel Syntax
void Pthread_testcancel (void);

The function is valid when the thread cancellation feature is enabled and the cancellation type is set to deferred mode pthread_testcancel() . This function does not work if it is called when the cancellation function is disabled pthread_testcancel() .

Be sure to insert only in the thread-safe sequence of the cancel Operation pthread_testcancel() . The pthread_testcancel() pthread standard also specifies several cancellation points, in addition to the cancellation points that are established programmatically by calling. For more details, see cancellation points.

pthread_testcancel return value

pthread_testcancel()no return value.

Explain:
There are two threads t1,t2, all to call the fun () function, the function content is: Fun ()
{
int Len;

...
Pthread_setcancelstate (pthread_cancel_enable,&ioldstate);
Pthread_testcancel ();
Len=read (...);

Pthread_setcancelstate (pthread_cancel_disable,&ioldstate);
...
}
The  pthread_setcancelstate() function simply changes the cancel state of this thread ( Note that this is the thread ). So T1 into the fun () function,
When executed to the Pthread_setcancelstate () function, only the cancel state of the T1 itself is changed, and the cancel state of the T2 cannot be changed. When a thread executes to the Pthread_testcancel () function, it does not necessarily cancel (exit) immediately. describe the process of canceling a thread: 1) Other threads send cancellation requests (cancellation request) to the target thread by calling the Pthread_cancel () function. 2) After the cancellation request is issued, depending on the cancel state of the target thread, determines whether the cancellation request will reach the target thread: A. If the cancel state of the target thread is pthread_cancel_enable (the default), the cancellation request reaches the target thread. B. If the cancel state of the target thread is pthread_cancel_disable, the cancellation request is placed in the queue. Until the cancel state of the target thread becomes pthread_cancel_enable, the cancellation request is taken from the queue and sent to the target thread. 3) When the cancellation request arrives at the target thread , it determines when the thread cancels, based on the cancel type of the target thread: A. If the target thread's cancel type is pthread_cancel_deferred (the default), the target thread will not be canceled immediately, but will not be canceled until the next cancellation point is executed. There are many system functions that are cancellation point, and a detailed list can be viewed with the man 7 pthreads on Linux. In addition to the listed cancellation Point,pthread_testcancel () is also a cancellation point. That is, when the target thread executes to the Pthread_testcancel () function, if the thread has received a cancellation request and its cancel type is pthread_cancel_deferred, then the thread will cancel (exit) in this function. The function is no longer returned, and the target thread is gone. B. If the cancel type of the target thread is pthread_cancel_asynchronous, the target thread is immediately canceled ("immediate" here simply means that the target thread does not have to wait for a function that belongs to cancellation point to be canceled. It will be canceled immediately after the dispatch, because the kernel scheduler will have a delay, so it does not guarantee the time "immediately". For example, describe the use of these functions related to thread cancellation:
voidThread_function (void*Arg) {/** * Threads are ready to perform some key work and do not want to be canceled during this process. * So first set the cancel state* of this thread to Disabled by Pthread_setcancelstate (). */pthread_setcancelstate (pthread_cancel_disable, NULL);/*Perform critical work*/.../** * Key work execution is complete and can be canceled. * Set the Cancel state* of this thread to Enabled by Pthread_setcancelstate (). */pthread_setcancelstate (pthread_cancel_enable, NULL);/** * Call the Pthread_testcancel () function to check if a cancel request is sent to this thread when the cancel state* is in the disabled state. * Cancel (exit) If you have any words. */Pthread_testcancel ();/** * PTHREAD_TESTCANCEL () returned, indicating that no cancellation was previously sent to this thread, * Continue with the rest of the work. * At this time, if there is a cancellation request sent to this thread, it will be executed to * cancellation point next time (such as sleep (), read (), write (), ... ) is canceled. */.../** * Starting from here, the function no longer contains cancellation point. * If a cancellation request is received, it cannot be canceled. So first set the cancel type* of this thread to asynchronous, and the cancellation request will be canceled immediately. */Pthread_setcanceltype (pthread_cancel_asynchronous, NULL);/*code that does not contain cancellation point*/...}


The Pthread_testcancel () function can be used to make linuxthread consistent with POSIX, and on the other hand, if there is no function in the thread function as a cancellation point, you can create the cancellation point artificially with pthread_testcancel (). Causes the thread to be canceled once it receives a cancellation request.

Canceling threads in Pthread

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.