Home > Enterprise >  C: Do I need to cancel a thread I'm done using?
C: Do I need to cancel a thread I'm done using?

Time:09-21

I'm creating a thread in C to check something off a webpage ONCE during runtime. Am I suppose to CLOSE this thread, or once it's done executing will it automatically be disposed?

--> Imports
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

--> Start thread 
pthread_t thread_id;

pthread_create(&thread_id, NULL, threadFunction, NULL);


---> Thread function

void *threadFunction(void *vargp) { 

    //Do something...
    
    return NULL;
}

CodePudding user response:

You do not need to consider using pthread_cancel unless the goal is to prematurely end the execution of a running thread.

In most cases, you are just wanting the thread to complete its work. You normally detect that a thread has completed by joining with it, using pthread_join.

If you are creating a thread that is not expected to end, or it doesn't matter when it ends, you can create a detached thread, or detach it after creation using pthread_detach. Then, the thread is not joinable.

Your sample code passes in NULL for the thread attributes, which causes pthread_create to use default attributes. You should check your system, but Linux will create joinable threads by default.

For most beginner projects, it is probably easiest to create joinable threads, and have the main thread call pthread_exit after spawning all the threads. This waits for each spawned thread to finish executing before the program terminates.

Otherwise, if there is summary work that the main thread needs to perform after the threads complete, it would wait on each thread with pthread_join until all the threads have returned. After the last thread returns, the main thread can do what it needs to do, and then exit.

CodePudding user response:

The documentation for pthread says this:

The thread is created executing start_routine with arg as its sole argument. If the start_routine returns, the effect shall be as if there was an implicit call to pthread_exit() using the return value of start_routine as the exit status. Note that the thread in which main() was originally invoked differs from this. When it returns from main(), the effect shall be as if there was an implicit call to exit() using the return value of main() as the exit status.

So there is no need to explicitly terminate thread.

  • Related