Pthread_join function and Linux thread

Source: Internet
Author: User
Pthread_join causes one thread to wait for the end of another thread.

Without pthread_join in the Code, the main thread will soon end and the entire process will end, so that the created thread will end without a chance to start execution. After pthread_join is added, the main thread will wait until the waiting thread ends, so that the created thread can be executed.

All threads have a thread ID. Its type is pthread_t. Call the pthread_self () function to obtain its own thread number. The following describes how to create a thread. By creating a thread, the thread will execute a thread function. The thread format must be declared as follows: void * thread_function (void *) the function for creating a thread is as follows: int pthread_create (pthread_t * restrict thread, const pthread_attr_t * restrict ATTR, void * (* start_routine) (void *), void * restrict Arg); The following describes the meaning of each parameter: thread: The created thread number. ATTR: The created thread attribute. This will be detailed later. Start_routine: the thread function to be run. Art: The parameter passed to the thread function. The following is a simple example of creating a thread:
# Include <pthread. h> # include <stdio. h>/* prints X's to stderr. the parameter is unused. does not return. */void * print_xs (void * unused) {While (1) fputc ('x', stderr); return NULL;}/* the main program. */INT main () {pthread_t thread_id;/* Create a New thread. the new thread will run the print_xsfunction. */pthread_create (& thread_id, null, & print_xs, null);/* print O's continuously to stderr. */while (1) fputc ('O', stderr); Return 0 ;}
During compilation, note that the thread creation function is in the libpthread. So library, so you need to import the library in the compilation command. Command: gcc-O createthread-lpthread createthread. C if you want to pass a parameter to the thread function, you can use its parameter Arg, whose type is void *. If you need to pass multiple parameters, you can take these parameters into a struct for transmission. In addition, because the type is void *, your parameters cannot be released in advance. The following problem is similar to the process created earlier, but the problem avoidance process is much more serious. If your main thread, that is, the thread that executes the main function, has exited before the launch of other county towns, the bug is immeasurable. The pthread_join function blocks the main thread until all threads have exited. Int pthread_join (pthread_t thread, void ** value_ptr); thread: the thread number waiting to exit the thread. Value_ptr: Return Value of the exit thread. The following example combines the preceding content:
Int main () {pthread_t thread1_id; pthread_t thread2_id; struct char_print_parms thread1_args; struct char_print_parms thread2_args;/* Create a New thread to print 30,000 X's. */threadshortargs.character = 'X'; threadshortargs.count = 30000; pthread_create (& thread1_id, null, & char_print, & threadshortargs);/* Create a New thread print to 20,000 O's. */thread2_args.character = 'O'; thread2_args.count = 20000; pthread_create (& thread2_id, null, & char_print, & thread2_args);/* Make sure the first thread has finished. */pthread_join (thread1_id, null);/* Make sure the second thread has finished. */pthread_join (thread2_id, null);/* now we can safely return. */return 0 ;}
The thread attributes mentioned above are described below. As mentioned above, you can use the pthread_join () function to block the main thread and wait for other threads to exit, so that the main thread can clean up the environment of other threads. However, some threads prefer to clean up the exit state, and they do not want the main thread to call pthread_join to wait for them. We call this type of thread attributes detached. If we set the attribute to null when calling the pthread_create () function, it indicates that we want the created thread to adopt the default attribute, that is, jionable. If you need to set the attribute to detached, refer to the following example:
# Include <stdio. h> # include <pthread. h> void * start_run (void * Arg) {// do some work} int main () {pthread_t thread_id; pthread_attr_t ATTR; pthread_attr_init (& ATTR); invoke (& ATTR, pthread_create_detached); pthread_create (& thread_id, & ATTR, start_run, null); pthread_attr_destroy (& ATTR); sleep (5); exit (0 );}
After the thread is set to joinable, you can call pthread_detach () to make it detached. But the opposite operation is not allowed. Also, if the thread has already called pthread_join (), then calling pthread_detach () will not have any effect. The thread can end with its own execution or call pthread_exit. In addition, thread A can be passively ended by thread B. This is achieved by calling pthread_cancel. Int pthread_cancel (pthread_t thread); 0 is returned if the function is successfully called. Of course, the thread is not passively ended by others. It can determine how to end by setting its own attributes. Passive termination of a thread can be divided into two types: asynchronous termination and synchronous termination. Asynchronous termination means that when other threads call pthread_cancel, the thread is terminated immediately. The end of synchronization will not end immediately, and it will continue to run until it reaches the next end point (Cancellation point ). When a thread is created by default, its attribute is synchronization termination. Call pthread_setcanceltype () to set the final state. Int pthread_setcanceltype (INT type, int * oldtype); State: the state to be set. It can be pthread_cancel_deferred or pthread_cancel_asynchronous. So how is the end point set? The most common creation endpoint is where pthread_testcancel () is called. This function does nothing except check the status at the end of synchronization. The preceding function is used to set the final state. You can also use the following function to set the termination type, that is, whether the thread can be terminated: int pthread_setcancelstate (INT state, int * oldstate); State: termination state, it can be pthread_cancel_disable or pthread_cancel_enable. You can understand the meaning of a word.

Finally, let's talk about the nature of the thread. In Linux, the new thread is not in the original process, but the system calls clone () through a system (). The system copies a process that is exactly the same as the original process and executes the thread function in the process. However, this copy process is different from that of fork. The copied process shares all the variables and runtime environment with the original process. In this way, the variable changes in the original process can be reflected in the copy process.
 

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.