Linux multithreading pthread

Source: Internet
Author: User

1. Development of Linux threads

As early as linux2.2 kernel. There are no threads in the real sense. At that time, the commonly used thread pthread in Linux was actually simulated by a process, that is, the fork was used to create a "light" process, in addition, there is a limit on the number of threads for such a lightweight process: a maximum of 4096 threads can run at the same time.
2.4 The kernel eliminates the number limit and allows the maximum number of processes to be dynamically adjusted during system running. At that time, the Linux thread library was used, the corresponding thread model is "one-to-one", and thread management is implemented in the kernel-based function library. This thread is widely used. But it is not compatible with POSIX. In addition, many problems such as signal processing and process ID have not been completely solved.
Similar to the new 2.6 kernel, process scheduling deletes inefficient algorithms in earlier versions through re-writing, and the kernel framework page is rewritten. Start to use the nptl (native POSIX thread Library) thread library, which has the following goals: POSIX compatibility, processing results and applications, startup overhead, low link overhead, it is Binary compatible with Linux thread applications, software and hardware scalability, and integration with C ++. All of this is a more complete multi-threaded Kernel Mechanism of 2.6.

2. Implementation of Linux threads

Basic operations on Linux threads
The main thread and related operations here are user space thread operations. In Linux, The pthread thread library is generally a set of common thread libraries, which are proposed by POSIX, therefore, it has good portability.
2.1 thread creation: the common function used to create a thread is pthread_create.

2.2 thread Exit:

1) After the thread is created, it starts to run the relevant thread functions. After the function is run, the thread exits. This is a way for the thread to exit: after running, it automatically exits;

2) Call the pthread_exit function to exit;

3) The exit function of the Process Termination function. Once the process is completed, all threads in the process will be terminated unconditionally.
Note: Under the default thread attribute, if a process has many threads running at the same time, after a thread exits, the resources occupied by the current thread will not be released with the termination of the thread. Because all threads in a process share resources.
There is also a common function in the thread: The pthread_join function can be used to suspend the current thread and wait until other threads end. In fact, this function is a thread-blocking function. The function that calls it will wait until the end of the waiting thread. When the function returns, the resources of the waiting thread are recycled.
Pthread_create function:

 


Pthread_exit Function

Pthread_join Function

Cancel a thread
Sometimes, we want a thread to request another thread to end, just like sending a signal to it. The thread can be used to complete this operation, but with the single processing, the thread also has a way to change its behavior when it is requested to end the execution.
Let's look at the function that requires a thread to end execution.

This definition clearly understands that given a thread identifier, we can ask to cancel it. However, canceling the receiving end of a linear process request is a little complicated, but it is not too complicated. You can use pthread_setcancelstate to set the canceling state of a linear program. The following is the definition of this function:


If the cancellation request is accepted, the thread enters the second control level-use pthread_setcanceltype to set the cancellation type.

A little note is that int pthread_cancel (pthread_t thread) is not supported in the android-ndk-r3; so it seems that there is no better way to force exit the thread.

========================================================== ========================================================== =

The Linux multi-threaded pthread function is declared in. Therefore, when using this function, you need to introduce this header file.

Thread Creation
1. Create

Int pthread_create (pthread_t * restrict TIDP, const pthread_attr_t * restrict ATTR, void * (* func) (void *), void * restrict Arg );

ATTR: the thread attributes include priority, initial stack size, and whether it should be a daemon thread.

Default Value: null.

TIDP is the thread to be created. After the creation is successful, tipd is the ID of the first thread.

Void * (* func) (void *) is a function pointer of the void * (*) (void *) type *)

Is a function type where the parameter is void * and the return value is also void. A simple example is as follows:

Void * thread_handler (void * Arg)

{

Return NULL;

}

Void * restrict ARG
The ARG parameter in is the void * (* func) (void *) function pointer parameter.

Supplement: The function declaration contains restrict, which is used by the CPU to optimize the function. The use of restrict ensures that no memory overlap exists between parameters using the restrict mark.

Obtains the ID of a thread.

Pthread_t pthread_self (void );

Wait for the specified thread to terminate

Int pthread_join (pthread_t tid, void ** status );

Statues returns the return value of the waiting thread.

There are three exit methods for a single thread

1. The thread returns (Return Method) from the startup routine. the return value is a ready-made exit code.

2. The thread is canceled by other threads in the same process.

3. The thread calls pthread_exit to exit. Void pthread_exit (void * rval_ptr)

Thread cleanup Handler

Void pthread_clean_push (void (* RTN) (void *), void * Arg)

Void pthread_clean_pop (iny excute)

The call sequence of the clearing function RTN is arranged by the pthread_clean_push function.

It is executed in the following situations:

1. When pthread_exit is called

2. Response to the cancellation request

3. When pthread_clean_pop is called with a non-zero execute Parameter

If the execute parameter is 0, the cleanup function is not called. In any case, pthread_clean_pop will delete the cleanup handler created last time by pthread_clean_push.

If the thread uses return to return data from the routine, the cleanup handler established by pthread_clean_push will not be executed.

Comparison between Linux thread and fork

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.