UNIX Environment Programming Learning notes (28)-multithreaded Programming (III): thread cancellation

Source: Internet
Author: User

Lienhua34
2014-11-24

1 Canceling a thread

Pthread provides the Pthread_cancel function for requesting cancellation of other threads in the same process.

#include <pthread.h>

int Pthread_cancel (pthread_t tid);

Return value: Returns 0 if successful, otherwise the error code is returned

The Pthread_cancel call does not immediately terminate the target thread, but simply makes a cancellation request to the target thread. The calling thread does not wait for the target thread to terminate, and by default the target thread continues to run after the cancellation request is made until the target thread reaches a cancellation point. A cancel point is a location where the thread checks for cancellation and acts as requested.

Let's take a look at a thread cancellation example. The main thread creates a new thread, and the new thread loops to sleep for 5 seconds and then returns 2. The main thread, after creating a new thread, sleeps 2 seconds and calls Pthread_cancel to request that the new thread be canceled. Finally gets the exit status of the new thread.

#include <stdlib.h>#include<stdio.h>#include<string.h>#include<pthread.h>void*My_thread (void*Arg) {    intI=0; printf ("[New thread]: I'll sleep 5 seconds.\n");  while(I <5) {Sleep (1); I= i +1; printf ("[New thread]:%d\n", i); } printf ("[New Thread]: Exit now.\n"); return((void*)0);}intMain (void){  interr;  pthread_t Tid; void*Tret; Err= Pthread_create (&tid, NULL, my_thread, NULL); if(Err! =0) {printf ("can ' t create thread:%s\n", Strerror (err)); Exit (-1); } Sleep (2); printf ("[main thread]: Cancel new thread.\n"); Err=Pthread_cancel (TID); if(Err! =0) {printf ("can ' t cancel thread:%s\n", Strerror (err)); Exit (-1); } Err= Pthread_join (tid, &Tret); if(Err! =0) {printf ("can ' t join with new thread:%s\n", Strerror (err)); Exit (-1); } Else {    if(pthread_canceled = =Tret) {printf ("new thread has been canceled.\n"); } Else{printf ("New Thread exit code:%d\n", (int) Tret); }} exit (0);}

Compile the program, generate and execute the file Pthread_cancel_demo,

gcc -o pthread_cancel_demo-pthread pthread_cancel_demo.clienhua34:demo$. /sleep51[main thread]: Cancel new thread.new thread has been canceled .

If a thread responds to a cancellation request, it is equivalent to calling the Pthread_exit function with the parameter pthread_canceled.

2 Thread Cancellation Properties

Earlier, you learned that you can control the properties of a thread through the pthread_attr_t structure. However, there are two properties that are canceled with the thread that are not contained in the pthread_attr_t structure, which are both de-selectable and de-typed.

2.1 Can cancel status

The Cancel State property is an enable property that controls whether the thread is responding to a cancellation request from another thread. The property can be pthread_cancel_enable, or pthread_cancel_disable. The cancellation properties of a thread are defaulted to the former. If set to the latter, the thread will not respond to the cancellation request, but the cancellation request is pending for the thread, and when the de-pthread_cancel_enable state becomes a second time, the thread will process all pending cancellation requests at the next cancellation point.

A thread can modify its callable state by calling the Pthread_setcancelstate function.

#include <pthread.h>

int pthread_setcancelstate (int state, int *oldstate);

Return value: Returns 0 if successful, otherwise returns the error number

This function sets the current de-oldstate state of the thread and returns the original cancellation state by using the.

Let's take a look at the example below, where we call the Pthread_setcancelstate function at the beginning of the new thread entry function My_thread of the PTHREAD_CANCEL_DEMO.C program to set the new thread's cancellation state to Pthread_ Cancel_disable.

#include <stdlib.h>#include<stdio.h>#include<string.h>#include<pthread.h>void*My_thread (void*Arg) {    intI=0; interr; Err=pthread_setcancelstate (pthread_cancel_disable, NULL); if(Err! =0) {printf ("[New thread]: Can ' t set cancel state:%s\n", Strerror (err)); } printf ("[New thread:disable cancel state.\n"); printf ("[New thread]: I'll sleep 5 seconds.\n");  while(I <5) {Sleep (1); I= i +1; printf ("[New thread]:%d\n", i); } printf ("[New Thread]: Exit now.\n"); return((void*)0);}intMain (void){  interr;  pthread_t Tid; void*Tret; Err= Pthread_create (&tid, NULL, my_thread, NULL); if(Err! =0) {printf ("can ' t create thread:%s\n", Strerror (err)); Exit (-1); } Sleep (2); printf ("[main thread]: Cancel new thread.\n"); Err=Pthread_cancel (TID); if(Err! =0) {printf ("can ' t cancel thread:%s\n", Strerror (err)); Exit (-1); } Err= Pthread_join (tid, &Tret); if(Err! =0) {printf ("can ' t join with new thread:%s\n", Strerror (err)); Exit (-1); } Else {    if(pthread_canceled = =Tret) {printf ("new thread has been canceled.\n"); } Else{printf ("New Thread exit code:%d\n", (int) Tret); }} exit (0);}

Compile the program, build and execute the Pthread_cancel_demo file,

 lienhua34:demo$ GCC -o Pthread_cancel_demo- pthread pthread_cancel_demo.clienhua34:demo$.  /pthread_cancel_demo[new thread:disable cancel state.[ New thread]: I'll  sleep  5   seconds. [New thread]:  1  [main thread]: Cancel New Thread. [New thread]:  2  [new thread]:  Span style= "color: #800080;" >3  [new thread]:  4  [new thread]:  5  [new thread]: Exit Now.new Thread exit code:  0  

Comparing the results of the above operation with the results from the previous section, we can see that the new thread has not responded to the cancellation request of the main thread after setting the Pthread_cancel_disable state to the new one.

2.2 Types that can be canceled

The above-mentioned thread will check to see if it is canceled when it arrives at a cancellation point. This type of cancellation is also known as deferred cancellation. In addition, there is a cancellation type that is asynchronous cancellation. When a thread's cancellation type is asynchronous, the thread can be canceled at any time.

A thread can modify a thread's cancellation type by calling Pthread_setcanceltype.

#include <pthread.h>

int pthread_setcanceltype (int type, int *oldtype);

Return value: Returns 0 if successful, otherwise returns the error number

Where the type parameter can be pthread_cancel_deferred (deferred cancellation), or pthread_cancel_asynchronous (asynchronous cancellation). The function sets the current un-removable type of the thread to type, and then returns the original, un-canceled type through the Oldtype parameter.

(done)

UNIX Environment Programming Learning notes (28)-multithreaded Programming (III): thread cancellation

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.