商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > C++ Linux平台如何实现多线程

C++ Linux平台如何实现多线程

  发布于2026-07-21 阅读(0)

扫一扫,手机访问

在Linux平台上用C++写多线程程序,其实没有想象中那么复杂。无论是老牌的POSIX线程库(pthread),还是C++11之后自带的线程库,都能帮你把任务拆开并行跑。不过,选哪个、怎么用,还得看你的项目背景和编译器支持情况。

C++ Linux平台如何实现多线程

先说一个前提:如果你的编译器支持C++11或更高版本,那直接用头文件是最省事的。因为C++11原生线程库把底层细节封装好了,不再需要手动调用pthread。下面这个例子很直观,就是一个简单的线程函数,在主线程里创建并等待它结束:

#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." << std::endl;
    return 0;
}

编译时别忘了加上-std=c++11-pthread(虽然C++11线程库在Linux上底层还是依赖pthread,但链接器需要这个标志):

g++ -std=c++11 -pthread your_file.cpp -o your_program

当然,如果项目里还在用老旧的C++标准,或者你更习惯直接操作线程ID,那pthread库依然是可靠的选择。用法差不多,只不过函数签名和线程管理方式略有不同:

#include 
#include 

void* helloFunction(void* arg) {
    std::cout << "Hello from a thread!" << std::endl;
    pthread_exit(NULL);
}

int main() {
    pthread_t thread_id;
    if (pthread_create(&thread_id, NULL, helloFunction, NULL) != 0) {
        std::cerr << "Error: unable to create thread" << std::endl;
        return 1;
    }
    pthread_join(thread_id, NULL);
    std::cout << "Thread has finished." << std::endl;
    return 0;
}

编译pthread版本时,直接用-lpthread链接库:

g++ your_file.cpp -o your_program -lpthread

两个版本的核心逻辑是一样的:定义一个函数作为线程入口,创建线程去执行它,然后主线程等待子线程完成。区别在于,C++11的std::thread对象更现代、更安全,而pthread更贴近底层,适合需要精细控制线程属性的场景。

最后必须说一句:多线程不是简单地把任务扔到线程里就完事了。数据竞争、死锁、条件变量同步……这些才是真正考验功力的地方。实际项目中,互斥锁(mutex)、条件变量(condition_variable)几乎是标配。如果你刚开始接触,建议先从简单的线程创建和join入手,再逐步引入同步机制,一步步踩坑,才能写出健壮的多线程代码。

本文转载于:https://www.yisu.com/ask/73160755.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注