Linux thread creation

Source: Internet
Author: User

First, the concept of threading

The process runs in separate address spaces, the process of sharing data between processes requires Mmap or interprocess signaling, and in this section we learn how to execute multiple threads in the address space of a process.

In some cases it is necessary to enter a simultaneous execution of multiple control processes at the same time, the thread is sent to the field, such as the implementation of a graphical interface to download software, need to interact with the user, wait and handle the user's mouse keyboard events, on the other hand, you need to download multiple files simultaneously, waits and processes data sent from multiple network hosts, which require a "wait-and-process" loop that can be used with multiple lines  process implementation, a thread is specifically responsible for interacting with the user, and several threads per thread are responsible for communicating with a network host.

The main function and the signal processing function are multiple control processes in the same process address space , Multithreading is also the case , But more flexible than the signal processing function, the signal processing function of the control process is only generated when the signal is recursive , after processing the signal is finished, and the multi-threaded control process can coexist for a long time, the operating system will be dispatched between the threads and switch as if you were scheduling and switching between multiple processes. Because multiple threads of the same process share the same address space,thisThe Text Segment (code snippet), data Segment (segment) are shared , and if a function is defined, Can be called in each thread , ifdefines a global variable that can be accessed in each thread, the threads also share the following process resources and environment:

1. File Descriptor Descriptor

2. How each signal is processed (sig_ign, SIG_DFL, or custom signal processing functions)

3. Current working directory

4. User ID and Group ID

but some of the resources are each thread's own copy :

1. thread ID (generated by library function <pthread.h> itself pthread_t (unsigned long long))

2. Context, including the values of the various registers. program counters and Stack pointers

3. Stack Space

4.errno variables

5. Signal Shielding Word

6. Scheduling priority

The line libraries function we are going to learn is defined by the POSIX Standard, called posixthread or pthread. Thread functions on Linux are located in the Libpthread shared library , so the-lpthread option is added at compile time .

Second, thread control

A. Creating A thread

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/7F/17/wKiom1cTLR3yxTdyAAAeC9uHV9M855.png "title=" QQ screenshot 20160417142918.png "alt=" Wkiom1ctlr3yxtdyaaaec9uhv9m855.png "/>

    return value: successfully returns 0, failure returns the error number. There is a errno, but this is provided for compatibility with other function interfaces, and the Pthread library itself does not use it, by return value return error code clearer

    in one thread pthread_create () after creating a new thread, the current thread from pthread_create () returns to continue down Execute, the code executed by the new thread is passed from us to pthread_create start_routine determines. start_routine arg parameter is passed to it, and the parameter is of type

void * void * , this start_routine returns, the thread exits , and other threads can call pthread_join () get start_routine return value, similar to the parent process called wait (2) Gets the exit status of the child process .

after pthread_create successfully returns, the ID of the newly created thread is filled in to the memory unit pointed to by the thread parameter . We knowThe type of the path process ID is pid_t, and the ID of each process is unique across the system , and getpid (2) can get the current processID, which is a positive integer value. The type of thread ID is thread_t, which only guaranteed to be unique in the current process, thread_t This type has different implementations in different systems, it could be an integer value, or it could be a struct , or could be an address ., so you cannot simply print as an integer printf, and call pthread_self (3) to get the ID of the current thread.

The attr parameter represents a thread property, and again does not delve into thread properties, all code examples are passed NULL to the attr parameter, which represents the default value for thread properties   .

Here is an example:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h>void* pthread_ Test (void* arg) {int I=0;while (i++<10) {printf ("This is thread! Pid:%d,tid:%u\n ", (int) getpid (), (unsigned long) pthread_self ()); sleep (1);} return NULL;} pthread_t Ptr;int Main () {int pthread_ret=pthread_create (&ptr,null,pthread_test,null), if (pthread_ret!=0) { printf ("Create Pthread error!\n,info is:%s\n", Strerror (Pthread_ret)); exit (Pthread_ret);} int I=0;while (i++<10) {printf ("This was Man thread Pid:%d,tid:%u!\n", (int) getpid (), (unsigned long Long) pthread_self ( ); sleep (1);} return 0;}

Operation Result:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/7F/17/wKiom1cTNfuB4N3bAAA8H7GMXnA863.png "title=" QQ screenshot 20160417150657.png "alt=" Wkiom1ctnfub4n3baaa8h7gmxna863.png "/>

On Linux, thethread_t type is an address value , and multiple threads that belong to the same process are getpid (2) can get the same process number , call pthread_self (3) The resulting thread number is not the same . because the pthread_create error code is not present in the errno, cannot straight perror (3) Print error message, you can strerror (3) The error code to the error message before printing.

if Any thread that calls exit or _exit terminates all threads of the entire process, since return from the main function is equivalent to calling exit , in order to prevent the newly created thread from terminating, before the main function return delay of 1 seconds, this is only a workaround, even if the main thread waits 1 seconds, the kernel will not necessarily dispatch the newly created thread execution,  below we will see a better way.

Study Questions : The main thread holds the ID of the newly created threads in a global variable ntid, if the newly created thread does not call the  pthread_self Instead of printing this ntid directly, can you achieve the same effect?

answer : The new thread's tid is actually saved in the space pointed to by the thread address (Figure 1) by testing to get threads created successfully. But sometimes we use the same global variable NTID to create multiple sub-processes at this point ntid must be the last Ntid value created (Figure 2), so only pthread_self can achieve the goal. ( my humble opinion)

Figure 1:

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/7F/15/wKioL1cTPPWxcP1JAAA885y9mxY649.png "title=" QQ screenshot 20160417152022.png "alt=" Wkiol1ctppwxcp1jaaa885y9mxy649.png "/>

Figure 2:

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/7F/18/wKiom1cTPFfSKZRqAAA_eneo7Jo762.png "title=" QQ screenshot 20160417153338.png "alt=" Wkiom1ctpffskzrqaaa_eneo7jo762.png "/>

b. Terminating a thread

If you need to terminate only one thread without terminating the entire process , there are three ways to do this:

1. return from the thread function . This method is not appropriate for the main thread, and return from the main function is equivalent to calling exit.

2. one thread can call Pthread_cancel to terminate another thread in the same process .

3. thread can be adjusted pthread_exit terminated .

pthread_cancel terminates a thread in both synchronous and asynchronous cases, which is more complex and is not introduced.

The following describes the usage of pthread_exit and pthread_join .

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/7F/16/wKioL1cTRF3y5omqAAAZb8UZlAI862.png "title=" QQ screenshot 20160417160458.png "alt=" Wkiol1ctrf3y5omqaaazb8uzlai862.png "/>



Linux thread creation

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.