发布于2026-07-18 阅读(0)
扫一扫,手机访问
在Linux环境下进行C++多线程开发,其实有不少成熟的选择。从最经典的POSIX线程到C++11引入的标准库线程,再到C++20的协程,每种方案背后都有其适用场景和设计哲学。下面就把这些方法从头到尾梳理一遍,看看在实际项目中该怎么选、怎么用。

pthreads 可以说是Linux多线程编程的“老前辈”了。它作为POSIX标准的一部分,提供了最底层、最直接的线程控制接口,尤其适合需要与C代码混编的场景。
首先得包含头文件 #include 。然后定义一个线程函数,返回值是 void*,参数也是 void*——这是pthreads的固定套路。创建线程时调用 pthread_create,传参包括线程ID、线程属性(通常传nullptr)、函数指针和参数。最后用 pthread_join 等待线程结束,回收资源。
#include
#include
void* thread_function(void* arg) {
std::cout << "Thread is running" << std::endl;
return nullptr;
}
int main() {
pthread_t thread_id;
int result = pthread_create(&thread_id, nullptr, thread_function, nullptr);
if (result != 0) {
std::cerr << "Error creating thread: " << result << std::endl;
return 1;
}
pthread_join(thread_id, nullptr);
std::cout << "Thread finished" << std::endl;
return 0;
}
从C++11开始,标准库直接提供了 std::thread,接口要现代化得多,也彻底告别了C风格的API。如果你写的是纯C++项目,这通常是首选。
头文件换成 #include 。线程函数可以是一个普通函数、lambda或者可调用对象。创建线程就是 std::thread thread(thread_function);,然后通过 thread.join() 等待结束。整个过程类型安全,也不需要手动管理pthread的各种属性。
#include
#include
void thread_function() {
std::cout << "Thread is running" << std::endl;
}
int main() {
std::thread thread(thread_function);
thread.join();
std::cout << "Thread finished" << std::endl;
return 0;
}
协程是C++20的重磅新特性,它提供了一种更轻量、更高效的并发模型。不同于线程的抢占式调度,协程是协作式的,可以在函数内部挂起和恢复执行,非常适合异步编程和I/O密集型任务。
头文件是 #include 。协程的核心是定义一个带有 promise_type 的返回类型,比如下面示例中的 Task 结构体。在协程函数体内,使用 co_await、co_return 等关键字控制流程。创建协程时直接调用函数即可,它不会立即执行全部代码,而是按照挂起点逐步推进。
#include
#include
struct Task {
struct promise_type {
Task get_return_object() { return {}; }
std::suspend_never initial_suspend() { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() {}
};
};
Task async_function() {
std::cout << "Coroutine is running" << std::endl;
co_await std::suspend_never{};
}
int main() {
async_function();
std::cout << "Coroutine finished" << std::endl;
return 0;
}
具体选哪种,还得看项目的需求、维护成本以及团队对C++标准的接受程度。一般来说,新项目优先考虑标准库线程,如果涉及到大量异步回调,协程会是个更优雅的解决方案。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8