Good day.

I read the article Programming for Linux: threads , it has an example of the use of revocation points and macros pthread_cleanup_{push|pop} . But when performing this example on my computer, it does not work exactly as it is written in the article. It says that the stream should display 4 lines and only then end, but for some reason it does not.

Here is an example:

 #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <pthread.h> #include <unistd.h> void exit_func(void * arg) { free(arg); printf("Freed the allocated memory.\n"); } void * thread_func(void *arg) { int i; void * mem; pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); mem = malloc(1024); printf("Allocated some memory.\n"); pthread_cleanup_push(exit_func, mem); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); for (i = 0; i < 4; i++) { sleep(1); printf("I'm still running!!!\n"); } pthread_cleanup_pop(1); } int main(int argc, char * argv[]) { pthread_t thread; pthread_create(&thread, NULL, thread_func, NULL); pthread_cancel(thread); pthread_join(thread, NULL); printf("Done.\n"); return EXIT_SUCCESS; } 

What could be the problem? Please clarify.
P.S. OS ALTLinux 5.1. I compile this way: gcc main.cpp -lpthread -o threads

    2 answers 2

    It says that the stream should display 4 lines and only then end.

    If it is written there - it is a lie. It's not just about speed. As soon as you make the CANCELABLE thread ... it is right there and is interrupted when you call sleep.

    Here is the Solaris documentation :

    Be careful to cancel. The pthreads standard specifies several cancellation points, including:

    • Programmatically, establish a thread cancellation point through a pthread_testcancel call .

    • Threads in pthread_cond_wait or pthread_cond_timedwait(3C) .

    • Threads blocked on sigwait (2).

    • Some standard library calls. In general, these can be functions. See the cancellation (5) man page for a list.

    If you go to the cancellation (5) and read, you can find in the list of sleep, pwrite and write. This will mean that the thread will be interrupted when you call printf or sleep, and in many other cases.

    Thus, the behavior of the example fully complies with the specification.

      The fact is that main runs faster than threads. before printf ("Done.n"); put sleep (10);

      • But this will spoil the meaning of the example. After ten seconds, there will be nothing to cancel :) - cy6erGn0m