Question: If I use the pthread\_create() call in an infinite while loop in main, does it create multiple threads each time or will it only create the 2 threads that I need?

```
while(1){ 
   pthread_create(&thread_1...);
   pthread_create(&thread_2...);
}

```

Answer: 
it creates multiple threads each time.
you can use `pthread_cancel` to cancel any thread from the process.

Below is one of many ways to handle the termination of thread upon some event/timeout etc..

```
#include <stdio.h>
#include <signal.h> // for sigaction
#include <stdlib.h> // for exit and 
#include <pthread.h> // for pthread
#include <string.h> // for memset

#define TIMEOUT 10

pthread_t tid1, tid2;

void* thread_function1(void *arg)
{
    while(1) 
    {
        printf(" thread_function1 invoked\n");
        sleep(1); //avoid heavy prints 
    }
}

void* thread_function2(void *arg)
{
    while(1)
    {
        printf(" thread_function2 invoked\n");
        sleep(1); //avoid heavy prints
    }
}   

static void timer_handler(int sig, siginfo_t *siginfo, void *context)
{
    printf("Inside handler function timeout happened \n");
    if( sig == SIGALRM)
    {
        pthread_cancel(tid1);
        pthread_cancel(tid2);
        //exit(0); to exit from main
    }
}

int main()
{
    int count = 0;
    void *status;

    struct sigaction act;
    memset (&act, '\0', sizeof(act));
    sigemptyset(&act.sa_mask);
    /* Use the sa_sigaction field because the handles has two additional parameters */
    act.sa_sigaction = timer_handler;
    /* The SA_SIGINFO flag tells sigaction() to use the sa_sigaction field, not sa_handler. */
    act.sa_flags = SA_SIGINFO;
    if (sigaction(SIGALRM, &act, NULL) < 0)
    {
        perror ("sigaction SIGALRM");
        return 1;
    }
    alarm (TIMEOUT);
    pthread_create(&tid1,NULL,thread_function1,NULL);
    pthread_create(&tid2,NULL,thread_function2,NULL);

    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    printf(" MIAN ENDS ...BYE BYE \n");
    return 0;
}

```