tt1.c

For more information about this program, see “Kernel timeouts with pthread_join()” in the Clocks, Timers, and Getting a Kick Every So Often chapter.

/*
 * tt1.c
*/

#include <stdio.h>
#include <pthread.h>
#include <inttypes.h>
#include <errno.h>
#include <sys/neutrino.h>

#define SEC_NSEC 1000000000LL // 1 billion nanoseconds in a second

void *
long_thread (void *notused)
{
    printf ("This thread runs for more than 10 seconds\n");
    sleep (20);
}

int
main (void) // ignore arguments
{
    uint64_t        timeout;
    struct sigevent event;
    int             rval;
    pthread_t       thread_id;

    // set up the event -- this can be done once
    
    // This or event.sigev_notify = SIGEV_UNBLOCK:
    SIGEV_UNBLOCK_INIT (&event);

    // create a thread
    pthread_create (&thread_id, NULL, long_thread, NULL);

    // set up for 10 second timeout
    timeout = 10LL * SEC_NSEC;

    TimerTimeout (CLOCK_MONOTONIC, _NTO_TIMEOUT_JOIN, &event, &timeout, NULL);

    rval = pthread_join (thread_id, NULL);
    if (rval == ETIMEDOUT) {
        printf ("Thread %d is still running after 10 seconds!\n",
                thread_id);
    }

    sleep (5);
    
   
    TimerTimeout (CLOCK_MONOTONIC, _NTO_TIMEOUT_JOIN, &event, &timeout, NULL);
    rval = pthread_join (thread_id, NULL);
    if (rval == ETIMEDOUT) {
        printf ("Thread %d is still running after 25 seconds (bad)!\n",
                thread_id);
    } else {
        printf ("Thread %d finished (expected!)\n", thread_id);
    }
}