Example of using the pthread_kill function in Linux to test whether a thread is alive

Source: Internet
Author: User
Tags exit in

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.