Linux 系统编程之四多线程编程

大纲

Pthread 多线程编程

查找头文件

在 Linux 系统里,pthread.h 头文件的位置一般是 /usr/include/pthread.h,可以通过以下命令查看头文件的位置

1
# whereis pthread.h

案例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

using namespace std;

void printids(const char *s) {
pid_t pid = getpid();
pthread_t tid = pthread_self();
printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int) pid, (unsigned int) tid, (unsigned int) tid);
}

void *thr_fn(void *args) {
printids("new thread: ");
return ((void *) 0);
}

int main() {
pthread_t ntid;
int err = pthread_create(&ntid, NULL, thr_fn, NULL);
if (err != 0) {
printf("can't create thread: %d\n", err);
exit(1);
}
printids("main thread: ");
sleep(1);
return 0;
}

编译代码

由于 pthread 不是 Linux 系统默认的库,因此链接时需要使用静态库 libpthread.a。简而言之,在使用 pthread_create() 创建线程,以及调用 pthread_atfork() 函数建立 fork 处理程序时,需要通过 -lpthread 参数链接该库,同时还需要在 C++ 源文件里添加头文件 pthread.h

提示

为了可以正常编译使用了 pthread 的项目代码,不同构建工具的使用说明如下:

若使用 G++ 编译 C++ 项目,则编译命令的示例如下:

1
2
# 编译代码
$ g++ main.cpp -o main -lpthread

若使用 CMake 构建 C++ 项目,则 CMakeLists.txt 配置文件的示例内容如下:

1
2
3
set(CMAKE_CXX_FLAGS "-std=c++11 -lpthread")

add_executable(main main.cpp)

运行结果

程序运行输出的结果如下:

1
2
main thread:  pid 6189 tid 342021952 (0x1462d740)
new thread: pid 6189 tid 324765440 (0x135b8700)