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.