简体   繁体   中英

C++ thread still alive after kill?

I have an issue: I create a thread to execute a command line and sometimes it takes a lot of time for waiting. So, I want to kill this thread and I implement below code:

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

void* doSomeThing(void *)
{
    cout<<"Begin execute"<<endl;
    system("svn info http://wrong_link_it's_take_a_lot_of_time_to_execute");
    return NULL;
}

int main() {
    pthread_t myThread;

    int err = pthread_create(&myThread,NULL, &doSomeThing,NULL);
    if(err != 0)
    {
        cout<<"Create thread not success"<<endl;
    }

    sleep(2);

    if(pthread_cancel(myThread) == 0)
    {
        cout<<"Thread was be kill"<<endl;
    }

    sleep(3);

    cout<<"End of program";

    return 0;
}

I'm using pthread_cancel to kill this thread and the line cout<<"Thread was be kill"<<endl; always appear after I execute. It is meant this thread being killed, but I saw the surprise result when I ran it on Eclipse (both on Ubuntu and Windows 7)

Anybody can explain to me why this thread still alive after kill and can you give me some method to resolve this issue.

Thank you.

cancelling a thread is not actually killing it. it just requests cancellation:

  pthread_cancel - send a cancellation request to a thread 

(from man pthread_cancel).

The pthread_cancel() function sends a cancellation request to the thread thread. Whether and when the target thread reacts to the cancellation request depends on two attributes that are under the control of that thread: its cancelability state and type.

As pointed out by Marcus Müller in his answer , pthread_cancel() not necessarily ends the thread addressed.

Do not use system() if you want to kill what had been run.

  1. Create your own new child process using fork() / exec*() .
  2. If it's time to end the child let the parent issue a kill() on the PID returned by fork() ing in 1.

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