Explain threads, understand the differences between processes and threads, and thread separation and binding properties

Source: Internet
Author: User
Tags constant function prototype posix terminates

One, what is the thread.

We know that processes operate in separate address spaces, and that sharing data between processes requires a mmap or interprocess communication mechanism, but there are situations where multiple control processes need to be executed simultaneously in a process, and the thread comes in handy.

In fact, there is no real thread in Linux, it is simulated by the process.

A process is the basic entity that is responsible for allocating system resources, which is the smallest unit of the operating system or process dispatch, the thread is the execution branch of the process, and the thread is executed within the process (address space).

Because multiple threads of the same process share the same address space, both code and data are shared, and if you define a function that can be invoked in each thread, and if you define a global variable that can be accessed in each thread, the threads also share the following process resources and environments:

(1) File descriptor
(2) Signal processing mode
(3) Current working directory
(4) User ID and group ID

But the following resources are thread-exclusive:

(1) Thread ID
(2) context, including the values of various registers, program counters and stack pointers
(3) Stack space
(4) errno variable
(5) Signal shielding Word
(6) Scheduling priority

The main features of the thread:

(1) When the thread is running, a temporary variable is generated, because the temporary variable is saved on the stack. So each thread has its own private stack structure.

(2) Each thread has its own contextual information

Ii. the difference between process and thread

(1) process is independent, each create a process, must have its own PCB, address space, page table and physical memory. But it doesn't have to be so cumbersome to create a thread, just create your own PCB.

(2) process is the basic entity that undertakes allocating system resources, the thread is the smallest unit of operating system or process scheduling.

(3) The process has a separate address space, and a process crashes without affecting other processes. And there is no separate address space between threads, and a thread hangs is equal to the whole process hanging off.

Third, the control code of the thread

The line threading function is defined by the POSIX standard, known as POSIX thread or pthread. The Linux thread function is located in the Libpthread shared library, so add the-lpthread option at compile time. To facilitate our inclusion of this option in makefile, the following figure:

(1). Creating Threads
We use the Pthread_create function when creating a thread
The function prototype is:

The Pthread_self function is used when creating the thread ID
The function prototype is:

     pthread_t pthread_self (void);

With the above knowledge, let's take a look at the specific code to create the thread:

The result of successful code execution is:

(2). Waiting thread
The function used by the wait thread is pthread_join, and the function prototype is:

int Pthread_join (pthread_t thread, void **retval);

void **retval refers to obtaining the exit result of a new thread. Pthread_join is used to wait in a blocking way

Its function is:
A. Guarantee the exit order when exiting
B. Retrieving resource conditions when a new thread exits
C. Get the correct exit return value when the new thread exits

Next, let's look at the relevant code for the related wait thread function

After the code runs successfully, the result is 4s and the following information is exported:

(3). Terminate thread

There are 3 ways to terminate a thread:
A: Return from inside the thread function. Note: The main thread exits and all threads exit
B: Terminate the thread with the Pthread_exit function. The function prototype is:

      void Pthread_exit (void *retval);

The specific code is as follows:

The result of successful code execution is: the thread terminates after 4s and the main thread join succeeds. Output the following results:

C: Using the Pthread_cancel function to cancel the thread, the function prototype is

    int Pthread_cancel (pthread_t thread);

The specific code is as follows:


After the successful execution of the code: 1s output The following information:

The return value at this time is-1 because the thread thread is being tuned by a different thread. Pthread_cancel with the exception of the end, the Value_ptr point to the unit. stored in
is the constant pthread_canceled. The value of the constant pthread_canceled in the Linux pthread Library is-1.

Four, threading separation and binding properties

A: threads are either binding or separate.

B: threads, regardless of how they are separated, execute within the process

C: A binding thread can be recovered by other threads of its resources and killed. Its storage resource is not released until it is reclaimed by another thread. Conversely, a detached thread cannot be recycled or killed by another thread, and its memory resources are automatically released by the system when it terminates.

D: By default, threads are created to be combined. In order to avoid memory leaks, each of the associative threads should either be shown to be recycled, call pthread_join, or be detached by calling the Pthread_detach function.

E: If a binding thread ends up running but is not join, its state is similar to a zombie process in progress, where a portion of the resource is not reclaimed, so the creator thread should tune ⽤ to wait for the thread to run, and get the thread's exit code and reclaim its resources.

F: Since the call to Pthread_join, if the thread is not running, the caller will be blocked, and in some cases we do not want to.

For example, in a Web server when the main thread creates a strand for each new connection request Cheng
When row processing, the main thread does not want to block because of the call to Pthread_join (because the connection request that comes after it continues to be processed)

Code Pthread_detach (Pthread_self ()) or parent thread Pthread_detach (thread_id) (non-blocking) can be added to the child thread for immediate return.
This sets the state of the child thread to separate (detached), so that all resources are automatically freed when the thread is run.

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.