Summary of process thread termination function in Linux multithreaded environment

  • 2020-05-15 03:24:18
  • OfStack

pthread_kill:

pthread_kill is different from kill in that it sends signal to the thread. , the default action of most signal is to terminate the process, so we need to use signal() to grab the signal and add the handler.


int pthread_kill(pthread_t thread, int sig);

Send an sig signal to the thread specified with ID. If there is no processing in the thread code, the whole process will be affected according to the default behavior of the signal. In other words, if you send SIGQUIT to a thread, but the thread does not implement the signal handler, the whole process will exit.

pthread_kill(threadid, SIGKILL) kills the entire process. To get the right behavior, you need to implement signal(SIGKILL,sig_handler) within the thread. So, if the int sig parameter is not 0, then 1 must know exactly what to do, and 1 must implement the thread's signal processing function, otherwise, it will affect the whole process.

What if int sig is 0? This is a reserved signal, and one function is to determine if the thread is still alive. Return value of pthread_kill: success :0 thread does not exist: ESRCH signal is invalid: EINVAL

Code:


int kill_rc = pthread_kill(thread_id,0);

if(kill_rc == ESRCH) 
    printf("the specified thread did not exists or already quit\n"); 

else if(kill_rc == EINVAL) 
    printf("signal is invalid\n"); 
else 
    printf("the specified thread is alive\n");
 

pthread_cancel

Function prototype:


int pthread_cancel(pthread_t thread);

Send an unexecuted request to thread. Returns 0 on success, otherwise non-0. Sending successfully does not mean that thread will terminate. Returns zero on success, error returns non-zero error code ESRCH: thread specified ID thread not found.

abort versus exit

exit does some unlocking: unlocking all static global objects, caching, closing all I/O channels, and then terminating the program. If a function is registered with atexit, the registered function is called in the reverse order of atexit. However, if the atexit function throws an exception, terminate is called directly.

abort: immediate terminate program without any cleanup.

Attached are the basic functions of threading:

----------------------------------------------------------------
POSIX function description
----------------------------------------------------------------
pthread_create create 1 thread
pthread_self finds its own thread ID
pthread_equal tests whether the two threads ID are equal
pthread_detach sets up threads to free resources
pthread_join waits for 1 thread
pthread_cancel terminates another thread
pthread_exit exits the thread without exiting the process
pthread_kill sends a signal to the thread
---------------------------------------------------------------


Related articles: