user11224591
user11224591

Reputation:

what happen if the main thread finish but peer threads are not?

I'm new to C and multithreading programming, just a question on what happen if the main thread finish but peer threads are not, does the process still wait until all peer threads finish or the process terminates immediately right after the main thread is done?

Upvotes: 0

Views: 1225

Answers (2)

Rachid K.
Rachid K.

Reputation: 5211

Here is an example program which illustrates the preceding answer on GLIBC/Linux operating system. The program creates a detached secondary thread and if it is not passed a parameter, the main thread exits otherwise it calls pthread_exit():

#include <pthread.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>


void *th_entry(void *p)
{
  int i;

  printf("Secondary thread starting...\n");

  for (i = 0; i < 5; i ++) {
    printf(".");
    fflush(stdout);
    sleep(1);
  }

  printf("\nSecondary thread exiting\n");

  return NULL;
}


int main(int ac, char *av[])
{
  int rc;
  pthread_t tid;

  printf("Main thread starting...\n");

  rc = pthread_create(&tid, NULL, th_entry, NULL);
  if (rc != 0) {
    errno = rc;
    fprintf(stderr, "pthread_create(): '%m' (%d)\n", errno);
    return 1;
  }

  // Detach the secondary thread
  rc = pthread_detach(tid);
  if (rc != 0) {
    errno = rc;
    fprintf(stderr, "pthread_detach(): '%m' (%d)\n", errno);
    return 1;
  }

  // Some dummy work
  sleep(1);

  if (av[1]) {
    printf("Main thread exiting\n");
    return 0;
  } else {
    printf("Main thread calling pthread_exit()\n");
    pthread_exit(NULL);
  }

  return 0;

}

Compile it:

$ gcc td.c -l pthread

When the program is not passed any parameter, the main thread calls pthread_exit() and the process ends when the secondary thread finishes.

$ ./a.out
Main thread starting...
Secondary thread starting...
.Main thread calling pthread_exit()
....
Secondary thread exiting
$

When the program is passed a parameter, the main thread calls exit() (it returns 0 but it is equivalent) and the process ends immediately terminating the secondary thread:

$ ./a.out 1
Main thread starting...
Secondary thread starting...
.Main thread exiting
$

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409176

When the main function returns, or you call exit, then the system will terminate the process and all threads running in that process.

If you have background (detached) threads that you want to keep running, you have to end the "main" thread only, not the process. How to do that is platform-dependent, but on POSIX platforms (e.g. Linux or macOS) then you call pthread_exit instead of exit.

If you don't have any background threads then you need to join all the running threads to keep them from being forcibly terminated.

Upvotes: 3

Related Questions