Have you used pthread_cleanup_push and pop? Undo with pthread_cancel does not work without them. You should use them in pairs, as in the example below. if you forget the one that it will not compile (fancy macros, one has "{" and the other has "}"). You can even set different levels of cleaning / ascent. In any case, they set a point with a big jump, which cancels the transition when the cancellation occurs (pretty cool). In addition, if your test program does not wait for the start or stop of the stream, you may not notice the cancellation.
Example:
#include <stdio.h> #include <stdlib.h> #include <pthread.h> static void *ThreadProc(void * arg); static void unwind(__attribute__ ((unused)) void *arg); int _fActive = 0; int main(int argc, char** argv) { pthread_t Thread; int nRet; nRet = pthread_create(&Thread, NULL, ThreadProc, NULL); printf("MAIN: waiting for thread to startup...\n"); while (_fActive == 0) nanosleep(&(struct timespec){ 0, 0}, NULL); printf("MAIN: sending cancel...\n"); nRet = pthread_cancel(Thread); printf("MAIN: waiting for thread to exit...\n"); while (_fActive) nanosleep(&(struct timespec){ 0, 0}, NULL); printf("MAIN: done\n"); return 0; } static void unwind(__attribute__ ((unused)) void *arg) { // do some cleanup if u want printf("THREAD: unwind (all threads, canceled or normal exit get here)\n"); _fActive = 0; } static void *ThreadProc(void * arg) { pthread_cleanup_push(unwind, arg); // optional : pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); printf("THREAD: Enter Sleep\n"); _fActive = 1; sleep(1000000); printf("THREAD: Exit Sleep (canceled thread never gets here)\n"); pthread_cleanup_pop(1); printf("THREAD: Exit (canceled thread never gets here)\n"); return NULL; }
Program output:
MAIN: waiting for thread to startup... THREAD: Enter Sleep MAIN: sending cancel... MAIN: waiting for thread to exit... THREAD: unwind (all threads, canceled or normal exit get here) MAIN: done
Note how canceling cancels ThreadProc at the cancel point of sleep () and only performs the unwind () function.
johnnycrash
source share