Josh
Josh

Reputation: 11

Multithreading in C/C++ without waiting for the thread to finish

All the examples that I have seen about multithreading uses this method in the main method to wait until the thread is done:

pthread_join(thread_id, NULL); 

But what if I don't want it to wait? I want my main function to continue as the thread is doing it's work, but at the same time, I don't want main to exit before the thread exists. Is this possible in C/C++?

Upvotes: 1

Views: 2962

Answers (1)

SKi
SKi

Reputation: 8466

If you want to avoid using pthread_join(), then pthread_detach() is an option. From man-page:

int pthread_detach(pthread_t thread);

The pthread_detach() function marks the thread identified by thread as detached. When a detached thread terminates, its resources are
automatically released back to the system without the need for
another thread to join with the terminated thread.

it does not prevent the thread from being terminated if the process terminates using exit(3) (or equivalently, if the main thread returns).

Upvotes: 1

Related Questions