Summary of Linux thread-related knowledge

Source: Internet
Author: User

1. Basic thread Introduction (1) Thread overview

Threads are similar to processes and allow applications to concurrently perform multiple tasks in a single mechanism. A process can contain multiple threads, and all threads in the same program share the same part of the global memory region, and there is no real level of hierarchy between threads. Threads in the same process can execute concurrently, and threads can execute in parallel if the processor is multicore, and if a thread is blocked by waiting for I/O operations, the other threads can still continue to run

(2) thread is better than the aspect of the process
Argv,environ
Main thread Stack
Stack of thread 3
Stack of Thread 2
stack of thread 1
Shared memory shared by function library
Heap
Uninitialized data segment
Initializing data segments
Text

. Information between processes is difficult to share. Because the parent-child process does not share memory except for the read-only snippet, some interprocess communication must be used to exchange information between processes
Call fork () to create a process with relatively high cost
Threads are a good solution to both of these problems
Easily and quickly share information between threads, simply copy the data to a shared (global or heap) variable
. Create a line turndown creating threads is typically 10 faster, and thread creation is faster because the fork creates the process when it needs to replicate multiple properties, and in the threads, the properties are shared.

(3) Create thread

When the program is started, the resulting process is only a single thread, which we call the main threads

#include<pthread.h>int pthread_create(pthread_t *thread,const pthread_attr_t *attr,void*(*start)(void *),void *arg);

The new thread begins execution by calling a function with ARG, and the thread that calls Pthread_create () resumes executing the statement after the call.

(4) Terminating a thread

You can terminate the running of a thread in the following way
. Thread Call Pthread_exit ()
The. Thread start function executes the return statement and returns the specified value
. Call Pthread_cancel () to cancel the thread
Any thread that calls exit () or the main thread executes a return statement will cause all threads in the process to terminate immediately
The Pthread_exit () function can terminate a thread, and its return value can be obtained by calling Pthread_join ()

#include<pthread.h>void pthread_exit(void *retval);

Calling Pthread_exit () is equivalent to executing a return in the start function of a thread, except that pthread_exit () can be called anywhere, and the parameter retval specifies the return value of the thread

(5) Get thread ID
#include<pthread.h>pthread_t pthread_self(void);

Thread IDs are primarily used in applications such as the following
The different pthreads functions use the thread ID to identify the target thread to manipulate.
In a specific application, the thread ID of a particular thread is used as a label for a dynamic data structure, which is useful for identifying the creator or main thread of a data structure, and for determining the specific threads that subsequently perform operations on the data structure

function pthread_equal () to check if two threads have the same ID

#include<pthread.h>int pthread_equal(pthread_t t1,pthread_t t2);//如果相同返回非0值,否则返回0
(6) Connecting a terminated thread

The function Pthread_join () waits for the thread to terminate

#include<pthread.h>int pthread_join(pthread_t thread,void **retval);//返回0调用成功,否则失败

If Pthread_join () passes in a thread ID that has been previously connected, it will cause unpredictable behavior, and when the same thread ID is reused for another new thread after participating in a single connection, the new thread may be connected again
If the thread is not detached, you should use Pthread_join () to connect to the thread, otherwise it will produce a zombie thread

Key points of the Pthrea_join () function
The relationship between threads is peer, so any thread can call Pthread_join () to connect to other threads
. Pthread_join () cannot be targeted to any thread, only a single thread can be connected

(6) Separation of threads

The threads are all connected by default, but sometimes we don't care about the state of the thread exit, we can call Pthread_detach () and pass the thread parameter to the identifier of the specified thread, marking it as detached

#include<pthread.h>int pthread_detach(pthread_t thread);//返回0成功,否则失败

Once a thread is in a detached state, it cannot use Pthread_join () to get its state, nor can it return to the connected state

(7) How to select a process or a thread in the application

Sharing data between threads is simple, and data sharing between processes requires more input
Creating a thread is much more than creating a process block.
When multithreaded programming, you need to ensure that the function that calls thread safety
A bug in one thread could compromise all threads in the process
Each thread is confiscating a limited virtual address space in the host process
In multi-threaded applications, you need to use the signal carefully
In addition to data, threads can also share file descriptors, signal disposition, current working directory, and user ID and group ID

Synchronization of Threads (1) Protection of shared variable access: Mutex amount

The main advantage of threading is the ability to share information through global variables, but this sharing is a cost. You must make sure that when multiple threads modify the same variable, no other thread is modifying the variable, and to avoid the problem of sharing variables when thread updates, you must use mutexes to ensure that only one thread can access a shared resource at the same time

(2) statically assigned mutex

A mutex can be allocated either as a static variable or dynamically at run time, and the mutex is a variable of type pthread_mutex_t and must be initialized before it can be used. For a statically allocated mutex, the Pthread_mutex_initializer is assigned to the mutex as shown in the following example

pthread_mutex_t = PTHREAD_MUTEX_INITIALIZER;
1. Lock and Unlock Mutex

After initialization, the mutex is in an unlocked state. function Pthread_mutex_lock () can lock a mutex
The function pthread_mutex_unlock () can unlock a mutex

#include<pthread.h>int pthread_mutex_lock(pthread_mutex_t *mutex);int pthread_mutex_unlock(pthread_mutex_t *mutex);//返回0成功,其他失败

To lock the mutex, you need to specify the mutex when calling Pthread_mutex_lock (), if the mutex is currently unlocked, the call will return immediately, and if the mutex is locked by another thread, the call will block until the mutex is unlocked
The function Pthread_mutex_unlock () unlocks the mutex that was previously locked by the calling thread

2. Performance of Mutex

Typically, threads take more time to do other work, with less locking unlocking the mutex, so using mutexes has no significant performance impact on most programs

3. The deadlock of the mutex

When a thread needs to access multiple shared resources at the same time, no resource is managed by a different mutex. Deadlocks can occur when more than one line Cheng the same set of mutexes. As shown
Thread A
1.pthread_mutex_lock (MUTEX1);
2.pthread_mutex_lock (MUTEX2);
Thread 2
1.pthread_mutex_lock (MUTEX2);
2.pthread_mutex_lock (MUTEX1);
Each thread succeeds in locking a mutex and then tries to lock the mutex that is locked for another thread, and then waits forever.
The simplest way to avoid this kind of deadlock problem is to define the hierarchical relationship of the mutex

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Summary of Linux thread-related knowledge

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.