C++ Linux多线程实践
作者:WarmHope
时间:2026-07-03
浏览:0
在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;
}
当然,实际项目里的多线程场景远比这些示例复杂——线程间通信、同步策略、死锁预防、性能调优,每个都是值得深入的方向。建议把基础知识打牢后,多动手做几个实际案例,经验会来得更快。
作者最新文章
endnote怎么引用中文参考文献格式设置教程
2026-10-14 17:25
sql条件判断字符串不包含某个字符串的方法详解
2026-10-13 17:39
漫蛙漫画官网
2026-10-13 13:19
漫蛙官网入口免费下载安装最新版
2026-10-13 13:18
漫蛙漫画登录页面在哪
2026-10-13 13:15
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































