简体   繁体   中英

pthread_cancel is not canceling a thread — C++

I'm trying to cancel a thread from main. It does not cancel immediately but takes 4seconds approximately. It should because I've set its cancel type to asynchronous from the default (deferred). Why?

#include <iostream>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
using namespace std;


void *thread_function(void *arg);
int main()
{
  int res;
  pthread_t a_thread;
  res = pthread_create(&a_thread, NULL, thread_function, NULL);
  sleep(5);
  printf("Canceling thread...\n");
  res = pthread_cancel(a_thread);
  printf("Waiting for thread to finish...\n");
  res = pthread_join(a_thread, NULL);
  pthread_exit(0);
}



void *thread_function(void *arg)
{
  int i, res;
  res = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  res = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  printf("thread_function is running\n");
  for(i = 0; i < 17; i++) {
    pthread_yield();
    printf("Thread is still running (%d)...\n", i);
    sleep(1);
  }
  pthread_exit(0);
}

You are cancelling the thread after waiting for 5 seconds, which is why your thread runs for 5 seconds.

On a side note, I discourage you from terminating threads with asynchronous cancel, because you don't know the state of the resources allocated by the thread when it terminates. I suggest you find another way to communicate with your thread and terminate it gracefully (using a condition variable for instance).

Here is my output:

thread_function is running
Thread is still running (0)...
Thread is still running (1)...
Thread is still running (2)...
Thread is still running (3)...
Thread is still running (4)...
Canceling thread...
Waiting for thread to finish...

After it's done with the sleep(5) it terminates the other thread. This all looks fine for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM