how to terminate a sleeping thread in pthread?

后端 未结 3 1030
春和景丽
春和景丽 2021-02-04 16:30

I have thread which sleeps for a long time, then wakes up to do something, then sleep again, like this:

while(some_condition)
{
    // do something
    sleep(100         


        
3条回答
  •  自闭症患者
    2021-02-04 16:46

    Did you use pthread_cleanup_push and pop? Canceling with pthread_cancel doesn't work without them. You must use them in pairs just like I did in the example below. if you forget one it wont compile (fancy macros, one has the '{' and the other has the '}'). You can even nest different levels of cleanup/pops. Anyway, they set a long jump point that cancel jumps to when cancel occurs (pretty cool). Also, if your test program does not wait for the thread to start or to stop, you may not notice the canceling happening.

    Example:

    #include 
    #include 
    #include 
    
    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
    

    Notice how the cancel blows out of ThreadProc at the cancel point sleep() and executes only the unwind() function.

提交回复
热议问题