/*
 * cancel.c
 *
 * Demonstrate use of synchronous cancellation using
 * pthread_testcancel.
 *
 */
#include <pthread.h>
#include "error.h"

static int counter;

/*
 * Loop until cancelled. The thread can be cancelled only
 * when it calls pthread_testcancel, which it does each 1000
 * iterations.
 */
void *
thread_routine (void *arg)
{
	for (counter = 0; ; counter++)
		if ((counter % 1000) == 0)
			pthread_testcancel ();
	return NULL;
}

void
main (int argc, char *argv[])
{
	pthread_t thread_id;
	void * result;
	int status;

	status = pthread_create (&thread_id, NULL, thread_routine, NULL);
	if (status != 0)
		FAILED_ERRNO (status);

	sleep (2);

	status = pthread_cancel (thread_id);
	if (status != 0)
		FAILED_ERRNO (status);

	status = pthread_join (thread_id, &result);
	if (status != 0)
		FAILED_ERRNO (status);

	if (result == PTHREAD_CANCELED)
		printf ("Thread cancelled at iteration %d\n", counter);
	else
		FAILED;

	PASSED;
}
