核心概念
在 Linux 系统中,并没有原生的'线程'概念,而是复用进程的数据结构和管理算法,通过轻量级进程(LWP)来模拟线程。内核层面只提供轻量级进程的系统调用接口,用户态需要线程功能时,则依赖 pthread 库进行封装。
每个 Linux 平台都自带 pthread 库,编写多线程代码时必须链接该库。注意,pthread_create 并非系统调用,编译时需添加 -pthread 参数。每个线程都有独立的 ID,主线程通常最后退出,需等待子线程完成。
基础实践
下面是一个简单的线程创建与执行示例。这里展示了如何传递字符串参数,以及如何使用 pthread_self() 获取当前线程 ID。
#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);
}
return nullptr;
}
int main() {
pthread_t tid;
// 此时 tid 未初始化,打印可能为随机值
cout << tid << endl;
pthread_create(&tid, nullptr, threadRoutine, (void*)"thread 1");
cout << tid << endl;
// 阻塞等待子线程结束
pthread_join(tid, );
;
}



