Hi all:
Can anybody tell my why this simple code which used pthread_cancel to kill another thread throws "terminate called without an active exception".
Yes , I used google but what I found is not what I want.
I want to kill thread at once so I use pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
thanks in advance
#include<stdio.h>
#include <pthread.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
void* s_thread(void*) {
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
int i = 0;
while (1) {
i++;
sleep(1);
cout << "in s_thread i = "<<i << endl;
}
}
void* threadwork(void*) {
pthread_t t;
int rc;
while (1) {
rc = pthread_create(&t, NULL, s_thread, NULL);
pthread_detach(t);
cout << "create" << endl;
sleep(1);
pthread_cancel(t);
cout << "cancel" << endl;
}
}
int main() {
pthread_t thread;
int rc;
void* status;
rc = pthread_create(&thread, NULL, threadwork, NULL);
if (rc) {
cout << "error pthread create";
exit(-1);
}
rc = pthread_join(thread, &status);
return 0;
}