C++ Linux多线程实践
在Linux下实现多线程,可采用传统的POSIX线程库或C++11标准提供的std::thread类。使用std::thread需要编译器支持C++11,通过创建线程对象执行函数,主线程调用join等待其结束,完成基本流程。此外,pthread库需链接-lpthread,两种方式均能高效实现在Linux下的多线程并发。
在Linux下写多线程程序,最常见的思路就是直接上POSIX线程库——也就是大名鼎鼎的pthread。当然,如果你用的编译器已经支持C++11或更高标准,那用标准库里的std::thread会更省事。先看一个最简单的例子,感受一下整个流程。

前提很简单:编译器得支持C++11及以上版本,因为从那个版本开始,C++才有了原生的线程支持。下面这段代码,用std::thread创建了一个线程,让它执行一个打印函数,主线程等它执行完毕再退出。
#include
#include
void helloFunction() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
std::thread t(helloFunction);
t.join();
std::cout << "Thread has finished execution." << std::endl;
return 0;
}
编译的时候别忘了加-pthread选项,用来启用POSIX线程支持:
g++ -std=c++11 -pthread your_program.cpp -o your_program
另一个常用方案是直接调用pthread的API。下面这个示例跟上面干的是同一件事,只是换了一套接口:
#include
#include
void* helloFunction(void* arg) {
std::cout << "Hello from a thread!" << std::endl;
return nullptr;
}
int main() {
pthread_t thread;
if (pthread_create(&thread, nullptr, helloFunction, nullptr) != 0) {
std::cerr << "Error: unable to create thread" << std::endl;
return 1;
}
pthread_join(thread, nullptr);
std::cout << "Thread has finished execution." << std::endl;
return 0;
}
编译这个版本同样需要链接pthread库:
g++ -pthread your_program.cpp -o your_program
多线程编程里最头疼的问题就是资源竞争——两个线程同时写同一个变量,结果谁也说不准。解决办法也很经典:加锁。C++11提供了std::mutex,pthread则有pthread_mutex_t。来看一个用互斥锁保护输出的例子:
#include
#include
#include
std::mutex mtx;
void printMessage(const std::string& msg) {
mtx.lock();
std::cout << msg << std::endl;
mtx.unlock();
}
int main() {
std::thread t1(printMessage, "Hello from thread 1!");
std::thread t2(printMessage, "Hello from thread 2!");
t1.join();
t2.join();
return 0;
}
当然,实际项目里的多线程场景远比这些示例复杂——线程间通信、同步策略、死锁预防、性能调优,每个都是值得深入的方向。建议把基础知识打牢后,多动手做几个实际案例,经验会来得更快。
LibreOffice桌面版提供Writer、Calc、Impress等办公组件,可本地处理文档并交换Office格式。了解实际功能、商用许可、兼容性检查和企业支持的区别。
Numbers macOS版用于预算、数据整理和可视化报告,支持公式、图表、数据透视表及iCloud协作。了解Excel文件交换、Mac安装条件和多端使用差异。
Qoder智能体工作台将编程任务、项目知识整理和自动化集中处理。本页介绍任务执行、Repo Wiki与结果审阅,区分Qoder IDE、系统安装选项和账户套餐,并提供官方下载入口。
微信Windows版适合电脑聊天、会话查找和文件传送。本页说明登录与文件管理、电脑办公优势,以及大文件失败、版本差异和本地记录的核对方法。
LibreOffice桌面版提供Writer、Calc、Impress等办公组件,可本地处理文档并交换Office格式。了解实际功能、商用许可、兼容性检查和企业支持的区别。
Qoder智能体工作台将编程任务、项目知识整理和自动化集中处理。本页介绍任务执行、Repo Wiki与结果审阅,区分Qoder IDE、系统安装选项和账户套餐,并提供官方下载入口。






