type
date
slug
category
icon
password
1. Pthread Overview2. The Pthreads API3. Compiling Threaded Programs4. Thread Management5. Mutex Variables6. Condition Variables7. Monitoring, Debugging, and Performance Analysis for Pthreads8. Topics Not Covered9. References and More Information
1. Pthread Overview
Why Threads?
CPU眼里的:进程、线程 | MMU系列 | 空间独立性 - 阿布的视频 - 知乎 https://www.zhihu.com/zvideo/1469706912229429248
从
MMU
的视角,重新认识线程和进程,了解“空间独立性”的基本硬件原理和使用场景网络服务器更多使用多进程,很少使用多线程
@ Linux程序设计(第四版)
优点
- 在编辑文档的同时对文档中的单词个数进行实时统计 → 编辑时同时知道工作进度
- 一个多线程的数据库服务器,这是一种明显的单进程服务多用户的情况。→ 多进程满足加锁和数据一致性要求复杂,而多线程容易的多
- 一个混杂着输入、计算和输出的应用程序,可以将这几个部分分离为3个线程来执行,从而改善程序执行的性能。
- 处理多个网络连接的服务器应用程序(由于线程的不安全,实际网络服务器多用多进程来实现)
缺点
- 编写多线程程序需要非常仔细的实际,时许细微的偏差和变量共享而引发错误
- 多线程调试困难得多,线程之间交互难以控制
- 计算任务分为多线程,需要多个处理器核,且不同部分运行同时计算
What is Pthread?
- Processes contain information about program resources and program execution state,
- This independent flow of control is accomplished because a thread maintains its own
ㅤ | Thread contain info |
• Process ID, process group ID, user ID, and group ID | ㅤ |
• Environment | ㅤ |
• Working directory | ㅤ |
• Program instructions | ㅤ |
• Registers | Registers |
• Stack | Stack pointer, Scheduling properties (such as policy or priority) |
• Heap | ㅤ |
• File descriptors | Thread specific data. |
• Signal actions | Set of pending and blocked signals |
• Shared libraries | ㅤ |
Inter-process communication tools (such as message queues, pipes, semaphores, or shared memory) | ㅤ |


So, in summary, in the UNIX environment a thread:
Exists within a process
and uses the process resources
- Has
its own independent flow of control
as long as its parent process exists and the OS supports it
- Duplicates only
the essential resources
it needs to be independently schedulable
- May
share the process resources
with other threads that act equally independently (and dependently)
Dies if the parent process dies
- or something similar
- Is
“lightweight
” because most ofthe overhead has already been accomplished
through the creation of its process.
other supplementation refer to this link.
What are Pthreads?
Historically
, hardware vendors have implemented their own proprietary versions of threads. These implementations differed substantially from each other
making it difficult for programmers to develop portable threaded applications.In order to take full advantage of the capabilities provided by threads,
a standardized programming interface
was required.- For
UNIX
systems, this interface has been specified by theIEEE POSIX 1003.1c standard
(1995).
- Implementations adhering to this standard are referred to as POSIX threads, or
Pthreads
.
- Most hardware vendors now offer Pthreads in addition to their proprietary API’s.
Pthreads are defined as a set of C language programming types and procedure calls, implemented with a
pthread.h
header/include file and a thread library - though this library may be part of another library, such as libc
, in some implementations.Why Pthread?
- Light Weight
Managing threads requires fewer system resources than managing processes.
For example, the following table compares timing results for the
fork()
subroutine and the pthread_create()
subroutine. Timings reflect 50,000 process/thread creations, were performed with the time
utility, and units are in seconds, no optimization flags.Platform | fork() | pthread_create() |
real | user | sys |
Intel 2.6 GHz Xeon E5-2670 (16 cores/node) | 8.1 | 0.1 |
Intel 2.8 GHz Xeon 5660 (12 cores/node) | 4.4 | 0.4 |
AMD 2.3 GHz Opteron (16 cores/node) | 12.5 | 1.0 |
AMD 2.4 GHz Opteron (8 cores/node) | 17.6 | 2.2 |
IBM 4.0 GHz POWER6 (8 cpus/node) | 9.5 | 0.6 |
IBM 1.9 GHz POWER5 p5-575 (8 cpus/node) | 64.2 | 30.7 |
IBM 1.5 GHz POWER4 (8 cpus/node) | 104.5 | 48.6 |
INTEL 2.4 GHz Xeon (2 cpus/node) | 54.9 | 1.5 |
INTEL 1.4 GHz Itanium2 (4 cpus/node) | 54.5 | 1.1 |
- Efficient Communications/Data Exchange
To achieve optimum computing performance by using pthread instead of MPI . For Pthreads there is
no intermediate memory copy
required because threads share the same address space within a single process.
There is no data transfer,
per se. It can be as efficient as simply passing a pointer
.- Overlapping CPU work with I/O
- Priority/real-time scheduling
- Asynchronous event handling
Examples
A perfect example is the typical
web browser
, where many interleaved tasks can be happening at the same time, and where tasks can vary in priority.Another good example is
a modern operating system
, which makes extensive use of threads. A screenshot of the MS Windows OS and applications using threads is shown below.
Designing Threaded Programs
Parallel program

- Programs having the following characteristics may be well suited for pthreads
- Several common models for threaded programs exist:
- Manager/worker: a single thread, the manager assigns work to other threads, the workers. Typically, the manager handles all input and parcels out work to the other tasks. At least two forms of the manager/worker model are common: static worker pool and dynamic worker pool.
- Pipeline: a task is broken into a series of suboperations, each of which is handled in series, but concurrently, by a different thread. An automobile assembly line best describes this model.
- Peer: similar to the manager/worker model, but after the main thread creates other threads, it participates in the work.
Shared Memory Model

Thread-safeness
Thread-safeness: in a nutshell, refers to an application’s ability to execute multiple threads simultaneously without “clobbering” shared data or creating “race” conditions.
For example, suppose that your application creates several threads, each of which makes a call to the same library routine:
- This library routine accesses/modifies a global structure or location in memory.
- As each thread calls this routine it is possible that they may try to modify this global structure/memory location at the same time.
- If the routine does not employ some sort of synchronization constructs to prevent data corruption, then it is not thread-safe.

2. The Pthreads API
The Pthreads API
he subroutines which comprise the Pthreads API can be informally grouped into four major groups:
- Thread management: Routines that work directly on threads - creating, detaching, joining, etc. They also include functions to set/query thread attributes (joinable, scheduling etc.)
- Mutexes: Routines that deal with synchronization, called a “mutex”, which is an abbreviation for “mutual exclusion”. Mutex functions provide for creating, destroying, locking and unlocking mutexes. These are supplemented by mutex attribute functions that set or modify attributes associated with mutexes.
- Condition variables: Routines that address communications between threads that share a mutex. Based upon programmer specified conditions. This group includes functions to create, destroy, wait and signal based upon specified variable values. Functions to set/query condition variable attributes are also included.
- Synchronization: Routines that manage read/write locks and barriers.
Naming conventions: All identifiers in the threads library begin with
pthread_
. Some examples are shown below.Routine Prefix | Functional Group |
pthread_ | Threads themselves and miscellaneous subroutines |
pthread_attr_ | Thread attributes objects |
pthread_mutex_ | Mutexes |
pthread_mutexattr_ | Mutex attributes objects. |
pthread_cond_ | Condition variables |
pthread_condattr_ | Condition attributes objects |
pthread_key_ | Thread-specific data keys |
pthread_rwlock_ | Read/write locks |
pthread_barrier_ | Synchronization barriers |
3. Compiling Threaded Programs
Compiling Threaded Programs
Several examples of compile commands used for pthreads codes are listed in the table below.

4. Thread Management
Creating and Terminating Threads
Routines:
pthread_create(thread,attr,start_routine,arg)
pthread_exit(status)
pthread_cancel(thread)
pthread_attr_init(attr)
pthread_attr_destroy(attr)
Creating Threads:
Initially, your
main()
program comprises a single, default thread. All other threads must be explicitly created by the programmer. pthread_create
creates a new thread and makes it executable. This routine can be called any number of times from anywhere within your code.pthread_create
arguments:pthread_create 调用成功返回值是0,但失败时并未遵循UNIX函数的管理返回-1。
- thread: An opaque, unique identifier for the new thread returned by the subroutine.
- attr: An opaque attribute object that may be used to set thread attributes. You can specify a thread attributes object, or NULL for the default values.
- start_routine: the C routine that the thread will execute once it is created.
- arg: A single argument that may be passed to start_routine. It must be passed by reference as a pointer cast of type void. NULL may be used if no argument is to be passed.
The maximum number of threads that may be created by a process
is implementation dependent.Thread Attributes:
By default, a thread is created with certain attributes. Some of these attributes can be changed by the programmer via the thread attribute object.
pthread_attr_init
and pthread_attr_destroy
are used to initialize/destroy the thread attribute object.Other routines are then used to query/set specific attributes in the thread attribute object. Attributes include:
- Detached or joinable state
- Scheduling inheritance
- Scheduling policy
- Scheduling parameters
- Scheduling contention scope
- Stack size
- Stack address
- Stack guard (overflow) size
- Some of these attributes will be discussed later.
Thread Binding and Scheduling:
Question: After a thread has been created, how do you know a) when it will be scheduled to run by the operating system, and b) which processor/core it will run on?
Click for answer
The Pthreads API provides several routines that may be used to specify how threads are scheduled for execution. For example, threads can be scheduled to run
FIFO (first-in first-out), RR (round-robin) or OTHER (operating system determines)
. It also provides the ability to set a thread’s scheduling priority value.These topics are not covered here, however a good overview of “how things work” under Linux can be found in the sched_setscheduler man page.
The Pthreads API does not provide routines for binding threads to specific cpus/cores.
However, local implementations may include this functionality - such as providing the non-standard
pthread_setaffinity_np
routine. Note that “_np” in the name stands for “non-portable”.Also, the local operating system may provide a way to do this. For example, Linux provides the
sched_setaffinity
routine.Terminating Threads & pthread_exit()
There are several ways in which a thread may be terminated:
- The thread returns normally from its starting routine. Its work is done.
- The thread makes a call to the
pthread_exit
subroutine - whether its work is done or not.
- The thread is canceled by another thread via the
pthread_cancel
routine.
- The entire process is terminated due to making a call to either the
exec()
orexit()
- If
main()
finishes first, without callingpthread_exit
explicitly itself
Usuage1: The
pthread_exit()
routine allows the programmer to specify an optional termination status parameter.Usuage2: In subroutines that execute to completion normally, you can often dispense with calling
pthread_exit()
- unless, of course, you want to pass the optional status code back.Discussion on calling
pthread_exit()
from main()
:- There is a definite problem if
main()
finishes before the threads it spawned if you don’t callpthread_exit()
explicitly. All of the threads it created will terminate becausemain()
is done and no longer exists to support the threads.
- By having
main()
explicitly callpthread_exit()
as the last thing it does,main()
will block and be kept alive to support the threads it created until they are done.
Example: Pthread Creation and Termination
Passing Arguments to Threads
The
pthread_create()
routine permits the programmer to pass one argument
to the thread start routine. For cases where multiple arguments must be passed, this limitation is easily overcome by creating a structure which contains all of the arguments
, and then passing a pointer to that structure in the pthread_create()
routine.All arguments must be passed by reference and cast to (void *).
Question: How can you safely pass data to newly created threads, given their non-deterministic start-up and scheduling?
Answer (Click to view.)
- Make sure that all passed data is
thread safe
- that it can not be changed by other threads. The three examples that follow demonstrate what not and what to do.*
Example 01 -Thread Argument Passing
根据谷歌代码命名规范,使用snake_case的命名方法,默认是驼峰命名方法。
C99下没有sleep(),因此通过在linux系统下,#include <unistd.h>,包括sleep方法
Example 02 -Thread Argument Passing
This example shows how to
setup/pass multiple arguments
via a structure. Each thread receives a unique instance of the structure.Example 03 -error passing
his example performs argument passing incorrectly. It passes the address of variable
t
, which is shared memory space and visible to all threads
. As the loop iterates, the value of this memory location changes, possibly before the created threads can access it.Joining and Detaching Threads
Routines:
pthread_join (threadid,status)
pthread_detach (threadid)
pthread_attr_setdetachstate (attr,detachstate)
pthread_attr_getdetachstate (attr,detachstate)
Joining:
“Joining” is one way to accomplish
synchronization
between threads. For example:The Pthread_join() subroutine blocks the calling threads until the specified threadid thread terminates.

status
if it was specified in the target thread’s call to pthread_exit()
.Joinable or Not?
When a thread is created, one of its attributes defines whether it is j
oinable or detached
. Only threads that are created as joinable can be joined. If a thread is created as detached, it can never be joined.To explicitly create a thread as joinable or detached, the
attr
argument in the pthread_create()
routine is used. The typical 4 step process is:
- Declare a pthread attribute variable of the
pthread_attr_t
data type
- Initialize the attribute variable with
pthread_attr_init()
- Set the attribute detached status with
pthread_attr_setdetachstate()
- When done, free library resources used by the attribute with
pthread_attr_destroy()
Detaching
The
pthread_detach()
routine can be used to explicitly detach a thread even though it was created as joinable.There is no converse routine.
Stack Management
Miscellaneous Routines
pthread_self ()
pthread_equal (thread1,thread2)
pthread_self
returns the unique, system assigned thread ID of the calling thread.pthread_equal
compares two thread IDs. If the two IDs are different 0 is returned, otherwise a non-zero value is returned.Note that for both of these routines, the thread identifier objects are opaque and can not be easily inspected. Because thread IDs are opaque objects, the C language equivalence operator == should not be used to compare two thread IDs against each other, or to compare a single thread ID against another value.
pthread_once (once_control, init_routine)
pthread_once
executes the init_routine
exactly once in a process. The first call to this routine by any thread in the process executes the given init_routine
, without parameters. Any subsequent call will have no effect.The
init_routine
routine is typically an initialization routine.The
once_control
parameter is a synchronization control structure that requires initialization prior to calling pthread_once
. For example:pthread_once_t once_control = PTHREAD_ONCE_INIT;
5. Mutex Variables
Overview
Function
- Mutex variables are one of the primary means of implementing thread
synchronization
and forprotecting shared data
when multiple writes occur. (Very often the action performed by a thread owning a mutex isthe updating of global variables
.)
- a safe way to ensure that when several threads update the same variable
Opr Steps
A typical sequence in the use of a mutex is as follows:
- Create and initialize a mutex variable
- Several threads attempt to lock the mutex
- Only one succeeds and that thread owns the mutex
- The owner thread performs some set of actions
- The owner unlocks the mutex
- Another thread acquires the mutex and repeats the process
- Finally the mutex is destroyed
When several threads compete for a mutex, the losers
block
at that call - an unblocking call is available with “trylock”
instead of the “lock” call.Creating and Destroying Mutexes
Routines:
pthread_mutex_init (mutex,attr)
pthread_mutex_destroy (mutex)
pthread_mutexattr_init (attr)
pthread_mutexattr_destroy (attr)
Usage:
Mutex variables must be declared with type
pthread_mutex_t
, and must be initialized before they can be used. There are two ways to initialize a mutex variable:- Statically, when it is declared. For example:
pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
- Dynamically, with the
pthread_mutex_init()
routine. This method permits setting mutex object attributes, attr.
The mutex is initially unlocked.
The attr object is used to establish properties for the mutex object, and must be of
type pthread_mutexattr_t
if used (may be specified as NULL to accept defaults). The Pthreads standard defines three optional mutex attributes:- Protocol: Specifies the
protocol
used to preventpriority
inversions for a mutex.
- Prioceiling: Specifies the priority
ceiling
of a mutex.
- Process-shared: Specifies the process sharing of a mutex.
Note that not all implementations may provide the three optional mutex attributes.
The
pthread_mutexattr_init()
and pthread_mutexattr_destroy()
routines are used to create and destroy mutex attribute objects respectively.pthread_mutex_destroy()
should be used to free a mutex object which is no longer needed.Locking and Unlocking Mutexes
Routines:
pthread_mutex_lock (mutex)
pthread_mutex_trylock (mutex)
pthread_mutex_unlock (mutex)
Usage:
The
pthread_mutex_lock()
routine is used by a thread to acquire a lock on the specified mutex variable. If the mutex is already locked by another thread, this call will block the calling thread until the mutex is unlocked.pthread_mutex_trylock()
will attempt to lock a mutex. However, if the mutex is already locked, the routine will return immediately with a “busy” error code. This routine may be useful in preventing deadlock conditions, as in a priority-inversion situation.pthread_mutex_unlock()
will unlock a mutex if called by the owning thread. Calling this routine is required after a thread has completed its use of protected data if other threads are to acquire the mutex for their work with the protected data. An error will be returned if:- If the mutex was already unlocked
- If the mutex is owned by another thread
There is nothing “magical” about mutexes…in fact they are akin to
a “gentlemen’s agreement” between participating threads
. It is up to the code writer to ensure that the necessary threads all make the the mutex lock and unlock calls correctly. The following scenario demonstrates a logical error:Lock
A = 2
Unlock
Lock
A = A+1
Unlock
A = A*B
Question: When more than one thread is waiting for a locked mutex, which thread will be granted the lock first after it is released?
Click for answer.
Unless thread
priority scheduling
(not covered) is used, the assignment will be left to the native system scheduler
and may appear to be more or less random
.Example: Using Mutexes
- This example program illustrates the use of mutex variables in a threads program that performs a dot product.
- The main data is made available to all threads through a globally accessible structure.
- Each thread works on a different part of the data.
- The main thread waits for all the threads to complete their computations, and then it prints the resulting sum.
6. Condition Variables
Overview
Functions
- Condition variables provide yet
another way for threads to synchronize
. While mutexes implement synchronization bycontrolling thread access to data
, condition variables allow threads to synchronize based uponthe actual value of data
.
- A condition variable is a way to achieve the same goal without polling.
How to Use
A condition variable is always used in conjunction with a
mutex lock.
A representative sequence for using condition variables is shown below.
Main Thread
Declare and initialize global data/variables which require synchronization (such as "count")
Declare and initialize a condition variable object
Declare and initialize an associated mutex
Create threads A and B to do work | |
Thread A
1. Do work up to the point where a certain condition must occur (such as "count" must reach a specified value)
2. Lock associated mutex and check value of a global variable
3. Call pthread_cond_wait() to perform a blocking wait for signal from Thread-B. Note that call to pthread_cond_wait() automatically and atomically unlocks the associated mutex variable so that it can be used by Thread-B.
4. When signalled, wake up. Mutex is automatically and atomically locked.
5. Explicitly unlock mutex
6. Continue | Thread B
1. Do work
2. Lock associated mutex
3. Change the value of the global variable that Thread-A is waiting upon.
4. Check value of the global Thread-A wait variable. If it fulfills the desired condition, signal Thread-A.
5. Unlock mutex.
6. Continue |
Main ThreadJoin / Continue | ㅤ |
Creating and Destroying Condition Variables
Routines:
pthread_cond_init (condition,attr)
pthread_cond_destroy (condition)
pthread_condattr_init (attr)
pthread_condattr_destroy (attr)
Usage:
Condition variables must be declared with type
pthread_cond_t
, and must be initialized before they can be used. There are two ways to initialize a condition variable:- Statically, when it is declared. For example:
pthread_cond_t myconvar = PTHREAD_COND_INITIALIZER;
- Dynamically, with the
pthread_cond_init()
routine. The ID of the created condition variable is returned to the calling thread through the condition parameter. This method permits setting condition variable object attributes, attr.
The optional attr object is used to set condition variable attributes. There is only one attribute defined for condition variables: process-shared, which allows the condition variable to be seen by threads in other processes. The attribute object, if used, must be of type
pthread_condattr_t
(may be specified as NULL to accept defaults). Note that not all implementations may provide the process-shared attribute.The
pthread_condattr_init()
and pthread_condattr_destroy()
routines are used to create and destroy condition variable attribute objects.pthread_cond_destroy()
should be used to free a condition variable that is no longer needed.Waiting and Signaling on Condition Variables
Routines:
pthread_cond_wait (condition,mutex)
pthread_cond_signal (condition)
pthread_cond_broadcast (condition)
Usage:
pthread_cond_wait()
blocks the calling thread until the specified condition is signalled. This routine should be called while mutex is locked, and it will automatically release the mutex while it waits. After signal is received and thread is awakened, mutex will be automatically locked for use by the thread. The programmer is then responsible for unlocking mutex when the thread is finished with it.
- Recommendation: Using a WHILE loop instead of an IF statement (see watch_count routine in example below) to check the waited for condition can help deal with several potential problems, such as:
- If several threads are waiting for the same wake up signal, they will take turns acquiring the mutex, and any one of them can then modify the condition they all waited for.
- If the thread received the signal in error due to a program bug
- The Pthreads library is permitted to issue spurious wake ups to a waiting thread without violating the standard.
- The
pthread_cond_signal()
routine is used to signal (or wake up) another thread which is waiting on the condition variable. It should be called after mutex is locked, and must unlock mutex in order forpthread_cond_wait()
routine to complete.
- The
pthread_cond_broadcast()
routine should be used instead ofpthread_cond_signal()
if more than one thread is in a blocking wait state.
- It is a logical error to call
pthread_cond_signal()
before callingpthread_cond_wait()
.
- Proper locking and unlocking of the associated mutex variable is essential when using these routines. For example:
- Failing to lock the mutex before calling
pthread_cond_wait()
may cause it NOT to block. - Failing to unlock the mutex after calling
pthread_cond_signal()
may not allow a matchingpthread_cond_wait()
routine to complete (it will remain blocked).
Example: Using Condition Variables
7. Monitoring, Debugging, and Performance Analysis for Pthreads
Monitoring and Debugging Pthreads
- Debuggers vary in their ability to handle Pthreads. The TotalView debugger is LC’s recommended debugger for parallel programs. It is well suited for both monitoring and debugging threaded programs.
- An example screenshot from a TotalView session using a threaded code is shown below.
- Stack Trace Pane: Displays the call stack of routines that the selected thread is executing.
- Status Bars: Show status information for the selected thread and its associated process.
- Stack Frame Pane: Shows a selected thread’s stack variables, registers, etc.
- Source Pane: Shows the source code for the selected thread.
- Root Window showing all threads
- Threads Pane: Shows threads associated with the selected process
Performance Analysis Tools
- There are a variety of performance analysis tools that can be used with threaded programs. Searching the web will turn up a wealth of information.
- At LC, the list of supported computing tools can be found at: hpc.llnl.gov/software.
- These tools vary significantly in their complexity, functionality and learning curve. Covering them in detail is beyond the scope of this tutorial.
- Some tools worth investigating, specifically for threaded codes, include:
- OpenSpeedShop
- TAU
- HPCToolkit
- PAPI
- Intel VTune Amplifier ThreadSpotter
8. Topics Not Covered
Topics Not Covered
Several features of the Pthreads API are not covered in this tutorial. These are listed below. See the Pthread Library Routines Reference section for more information.
- Thread Scheduling
- Implementations will differ on how threads are scheduled to run. In most cases, the default mechanism is adequate.
- The Pthreads API provides routines to explicitly set thread scheduling policies and priorities which may override the default mechanisms.
- The API does not require implementations to support these features.
- Keys: Thread-Specific Data
- As threads call and return from different routines, the local data on a thread’s stack comes and goes.
- To preserve stack data you can usually pass it as an argument from one routine to the next, or else store the data in a global variable associated with a thread.
- Pthreads provides another, possibly more convenient and versatile, way of accomplishing this through keys.
- Mutex Protocol Attributes and Mutex Priority Management for the handling of “priority inversion” problems.
- Condition Variable Sharing—across processes
- Thread Cancellation
- Threads and Signals
- Sychronization constructs—barriers and locks
9. References and More Information
Original Author: Blaise Barney; Contact: [email protected], Livermore Computing.
"Pthreads Programming". B. Nichols et al. O'Reilly and Associates.
"Threads Primer". B. Lewis and D. Berg. Prentice Hall
"Programming With POSIX Threads". D. Butenhof. Addison Wesley
"Programming With Threads". S. Kleiman et al. Prentice Hall
Pthread:POSIX 多线程程序设计 (中文翻译)
pthread详解 中文阅读笔记-详细
- Author:felixfixit
- URL:http://www.felixmicrospace.top/1c122aae1cab43cdbc60731eb5c0013e
- Copyright:All articles in this blog, except for special statements, adopt BY-NC-SA agreement. Please indicate the source!