发布于2026-07-03 阅读(0)
扫一扫,手机访问
在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;
}
当然,实际项目里的多线程场景远比这些示例复杂——线程间通信、同步策略、死锁预防、性能调优,每个都是值得深入的方向。建议把基础知识打牢后,多动手做几个实际案例,经验会来得更快。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8