Pthread_join pthread_exit thread Linux function thread exit thread wait

Source: Internet
Author: User

Next, let's take a look at the thread exit function and wait function.

# Include <pthread. h>

Void pthread_exit (void * value_ptr );

Value_ptr: the return value of the thread. Pthread_join () is detected.

Function: the thread exits.

# Include <pthread. h>

Int pthread_join (pthread_t thread, void ** value_ptr );

Function: wait until the specified thread ends.

Return Value: 0 is returned for success.

Parameters:

Thread: ID of the waiting thread (identifier)

Value_ptr: a custom pointer used to save the return value of the waiting thread.

This function is a thread-blocking function. The function that calls it will be blocked until the end of the waiting thread. When the function returns a value, the resources of the waiting thread will be recycled.

Let's look at an example:

# Include <stdio. h>

# Include <stdlib. h>

 

Void * th_fun1 (void * Arg)

{

Int I = 10/2;

Printf ("% s", ARG );

While (I --> 0)

Fputs ("New thread1 \ n", stdout );

Pthread_exit (void *) 1 );

}

 

Void * th_fun2 (void * Arg)

{

Int I = 10/2;

Printf ("% s", ARG );

While (I --> 0)

Fputs ("New thread 2 \ n", stdout );

Pthread_exit (void *) 2 );

}

 

Int main ()

{

Int ret;

Pthread_t tid1, tid2;

If (ret = pthread_create (& tid1, null, th_fun1, "New thread 1 created! \ N ") =-1)

{

Perror ("pthread_createerror ");

Exit (exit_failure );

}

If (ret = pthread_create (& tid2, null, th_fun2, "New thread 2 created! \ N ") =-1)

{

Perror ("pthread_createerror ");

Exit (exit_failure );

}

Void * fret1;

Void * fret2;

Pthread_join (tid1, & fret1 );

Pthread_join (tid2, & fret2 );

Printf ("fret1 = % d \ n", (INT) fret1 );

Printf ("fret2 = % d \ n", (INT) fret2 );

Return 0;

}

 

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.