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;
}

Hi everybody:

I debug the above program , and found that the thread will block at pthread_create for a short time and then throws "terminate called without an active exception".

But why pthread_create will block?
I think if it create sucessfully ,return 0; else return non-zero
why block

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.