how to terminate a sleeping thread in pthread?

后端 未结 3 1034
春和景丽
春和景丽 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:42

    The classic UNIX condition variable is the self-pipe.

    int fds[2];
    pipe2(fds, O_NONBLOCK);  // requires newish kernel and glibc; use pipe + 2*fcntl otherwise
    
    child:
        while (some_condition) {
            // do something
            struct pollfd pd = { .fd = fds[0], .events = POLLIN };
            int rc;
            char c;
            while ((rc = poll(&pd, 1, 1000000)) == -1 && errno == EINTR)
                // not entirely correct; 1000000 should be decreased according to elapsed time when repeating after a signal interruption
                ;
            if (rc > 0 && (pd.revents & POLLIN) && read(fds[0], &c, 1) >= 0)
                break;
        }
    
    parent:
        cancel() {
            char c = 0;
            write(fds[1], &c, 1);
        }
    

    Yeah, it's a lot of fiddly (and untested) code. You should probably just use pthread_cond_wait, it requires a pthread_mutex_t and a pthread_cond_t but is much easier.

提交回复
热议问题