Search code examples
cpthreadsposix

POSIX pthread programming


I have to code a multithreaded(say 2 threads) program where each of these threads do a different task. Also, these threads must keep running infinitely in the background once started. Here is what I have done. Can somebody please give me some feedback if the method is good and if you see some problems. Also, I would like to know how to shut the threads in a systematic way once I terminate the execution say with Ctrl+C.

The main function creates two threads and let them run infinitely as below.

Here is the skeleton:

void    *func1();
void    *func2();

int main(int argc, char *argv[])
{   

    pthread_t th1,th2;
    pthread_create(&th1, NULL, func1, NULL);
    pthread_create(&th2, NULL, func2, NULL);

    fflush (stdout);
    for(;;){
    }
    exit(0); //never reached
}

void *func1()
{
    while(1){
    //do something
    }
}

void *func2()
{
    while(1){
    //do something
    }
} 

Thanks.

Edited code using inputs from the answers: Am I exiting the threads properly?

#include <stdlib.h>     /*  exit() */
#include <stdio.h>      /* standard in and output*/
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <signal.h>
#include <semaphore.h>

sem_t end;

void    *func1();
void    *func2();

void ThreadTermHandler(int signo){
    if (signo == SIGINT) {
        printf("Ctrl+C detected !!! \n");
        sem_post(&end);
        }
}
void *func1()
{
    int value;
    for(;;){
        sem_getvalue(&end, &value);
        while(!value){
            printf("in thread 1 \n");
        }
    }
    return 0;
}

void *func2()
{
    int value;
    for(;;){
        sem_getvalue(&end, &value);
        while(!value){
            printf("value = %d\n", value);
        }
    }
    return 0;
}

int main(int argc, char *argv[])
{


    sem_init(&end, 0, 0);
    pthread_t th1,th2;
    int value  = -2;
    pthread_create(&th1, NULL, func1, NULL);
    pthread_create(&th2, NULL, func2, NULL);

    struct sigaction sa;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_SIGINFO;
    sa.sa_sigaction = ThreadTermHandler;
    // Establish a handler to catch CTRL+c and use it for exiting.
    if (sigaction(SIGINT, &sa, NULL) == -1) {
        perror("sigaction for Thread Termination failed");
        exit( EXIT_FAILURE );
    }

    /* Wait for SIGINT. */
    while (sem_wait(&end)!=0){}
    //{
        printf("Terminating Threads.. \n");
        sem_post(&end);
                sem_getvalue(&end, &value);
        /* SIGINT received, cancel threads. */
        pthread_cancel(th1);
        pthread_cancel(th2);
        /* Join threads. */
        pthread_join(th1, NULL);
        pthread_join(th2, NULL);
    //}
    exit(0);
}

Solution

  • There are mainly two approaches for thread termination.

    • Use a cancellation point. The thread will terminate when requested to cancel and it reaches a cancellation point, thus ending execution in a controlled fashion;
    • Use a signal. Have the threads install a signal handler which provides a mechanism for termination (setting a flag and reacting to EINTR).

    Both approaches has caveats. Refer to Kill Thread in Pthread Library for more details.

    In your case, it seems a good opportunity to use cancellation points. I will work with a commented example. The error-checking has been omitted for clarity.

    #define _POSIX_C_SOURCE 200809L
    #include <pthread.h>
    #include <signal.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    
    void sigint(int signo) {
        (void)signo;
    }
    
    void *thread(void *argument) {
        (void)argument;
        for (;;) {
            // Do something useful.
            printf("Thread %u running.\n", *(unsigned int*)argument);
    
            // sleep() is a cancellation point in this example.
            sleep(1);
        }
        return NULL;
    }
    
    int main(void) {
        // Block the SIGINT signal. The threads will inherit the signal mask.
        // This will avoid them catching SIGINT instead of this thread.
        sigset_t sigset, oldset;
        sigemptyset(&sigset);
        sigaddset(&sigset, SIGINT);
        pthread_sigmask(SIG_BLOCK, &sigset, &oldset);
    
        // Spawn the two threads.
        pthread_t thread1, thread2;
        pthread_create(&thread1, NULL, thread, &(unsigned int){1});
        pthread_create(&thread2, NULL, thread, &(unsigned int){2});
    
        // Install the signal handler for SIGINT.
        struct sigaction s;
        s.sa_handler = sigint;
        sigemptyset(&s.sa_mask);
        s.sa_flags = 0;
        sigaction(SIGINT, &s, NULL);
    
        // Restore the old signal mask only for this thread.
        pthread_sigmask(SIG_SETMASK, &oldset, NULL);
    
        // Wait for SIGINT to arrive.
        pause();
    
        // Cancel both threads.
        pthread_cancel(thread1);
        pthread_cancel(thread2);
    
        // Join both threads.
        pthread_join(thread1, NULL);
        pthread_join(thread2, NULL);
    
        // Done.
        puts("Terminated.");
        return EXIT_SUCCESS;
    }
    

    The need for blocking/unblocking signals is that if you send SIGINT to the process, any thread may be able to catch it. You do so before spawning the threads to avoid having them doing it by themselves and needing to synchronize with the parent. After the threads are created, you restore the mask and install a handler.

    Cancellation points can be tricky if the threads allocates a lot of resources; in that case, you will have to use pthread_cleanup_push() and pthread_cleanup_pop(), which are a mess. But the approach is feasible and rather elegant if used properly.