Original article address:
In the afternoon, I wrote the pthread_kill function to check whether a thread is still alive.ProgramIn Linux, GCC is compiled.CodePaste it below:
/*******************************Pthread_kill.c*******************************/
/* * **************************** Pthread_kill.c ********* ********************* */
# Include < Stdio. h >
# Include < Stdlib. h >
# Include < Pthread. h >
# Include < Errno. h >
Void * Func1 () /* Exit in 1 second */
{
Sleep ( 1 );
Printf ( " Thread 1 (ID: 0x % x) exits. \ N " , (Unsigned Int ) Pthread_self ());
Pthread_exit (( Void * ) 0 );
}
Void * Func2 () /* Exit in 5 seconds */
{
Sleep ( 5 );
Printf ( " Thread 2 (ID: 0x % x) exits. \ N " , (Unsigned Int ) Pthread_self ());
Pthread_exit (( Void * ) 0 );
}
Void Test_pthread (pthread_t tid) /* Pthread_kill return value: Success (0) the thread does not exist (esrch) The signal is invalid (einval) */
{
Int Pthread_kill_err;
Pthread_kill_err = Pthread_kill (TID, 0 );
If (Pthread_kill_err = Esrch)
Printf ( " The thread with the ID 0x % x does not exist or has exited. \ N " , (Unsigned Int ) Tid );
Else If (Pthread_kill_err = Einval)
Printf ( " The sent signal is invalid. \ N " );
Else
Printf ( " The thread with the ID 0x % x is still alive. \ N " , (Unsigned Int ) Tid );
}
Int Main ()
{
Int RET;
Pthread_t tid1, tid2;
Pthread_create ( & Tid1, null, func1, null );
Pthread_create ( & Tid2, null, func2, null );
Sleep ( 3 ); /* After creating two processes for three seconds, test whether they are still alive. */
Test_pthread (tid1 ); /* Test whether a thread with the ID of tid1 exists */
Test_pthread (tid2 ); /* Test whether a thread with the ID of tid2 exists */
Exit ( 0 );
}
End