0

I am wondering if the program exit after main routine terminate while other threads are running.

I want to find a way to keep the program running til other threads terminate.

I try detach the threads but it doesn't work.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

using namespace std;

#define threads 5

void *ThreadFunction(void *arg) {
    pthread_detach(pthread_self()); // detach thread
    int n = *((int *)arg);
    printf("Hello World, %d \n", n );
}



int main() {

    pthread_t *thread = new pthread_t[threads];
    int *data = new int[threads];

    for (int t = 0; t < threads; t++) {
        data[t] = t + 1; // from 1 to 5
        pthread_create(thread + t, NULL, ThreadFunction, (void *)(data+t));
    }
    sleep(1);
    free(thread);
    free(data);
    return 0;
}

If I remove the sleep(1) statement, it can't output all the result I wanted. enter image description here

Z.Lun
  • 247
  • 1
  • 2
  • 20
  • 1
    Does this answer your question? [pthread\_detach question](https://stackoverflow.com/questions/6042970/pthread-detach-question) – John Bollinger Apr 19 '23 at 21:01
  • 1
    To summarize the answers to the dupe target: the whole program, including any detached threads, terminates when `exit()` is called by any thread or when execution returns from the initial call to `main()`, among other possibilities. The initial call to `main()` can terminate without terminating the whole program by calling `pthread_exit()`. – John Bollinger Apr 19 '23 at 21:04

0 Answers0