背景
Linux 中没有真正的线程概念,而是复用进程数据结构和管理算法,用进程模拟线程。只有轻量级进程(LWP),不会提供线程的调用接口,而是提供轻量级进程的系统调用接口。
用户需要线程调用时,使用 pthread 库封装了轻量级进程调用接口,可以直接使用线程接口。
- 每个 Linux 平台自带 pthread 库
- 编写多线程代码需要链接 pthread 库
线程接口

每个线程都有自己的 ID。pthread_create 不是系统调用,需链接 -pthread。
进程控制
#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;
void* threadRoutine(void* args) {
const char* str = (const char*)args;
cout << str << endl;
int cnt = 5;
while(cnt--) {
cout << "thread id :" << pthread_self() << endl;
sleep(1);
}
}
int main() {
pthread_t tid;
cout << tid << endl;
pthread_create(&tid, nullptr, *threadRoutine, (void*)"thread 1");
cout << tid << endl;
pthread_join(tid, );
;
}









