Linux环境下C++如何实现多线程

Linux环境下C++如何实现多线程

本文将演示如何在Linux环境下使用C++和POSIX线程库(pthread)创建多线程程序。 首先,确保你的系统已安装pthread库(大多数Linux发行版默认安装)。

创建一个名为multithread_example.cpp的文件,并粘贴以下代码:

#include <iostream>#include <pthread.h>#include <string>// 线程函数void* thread_function(void* arg);int main() {    pthread_t thread1, thread2;    int result1, result2;    // 创建线程    result1 = pthread_create(&thread1, NULL, thread_function, (void*)"Thread 1");    result2 = pthread_create(&thread2, NULL, thread_function, (void*)"Thread 2");    if (result1 != 0 || result2 != 0) {        std::cerr << "Error creating thread" << std::endl;        return 1;    }    // 等待线程结束 (可选,取决于你的程序逻辑)    pthread_join(thread1, NULL);    pthread_join(thread2, NULL);    std::cout << "All threads finished." << std::endl;    return 0;}void* thread_function(void* arg) {    std::string thread_name = static_cast<const char*>(arg);    std::cout << thread_name << " is running." << std::endl;    // 在这里添加你的线程任务代码    return NULL;}

登录后复制

文章来自互联网,不代表电脑知识网立场。发布者:,转载请注明出处:https://www.pcxun.com/n/581161.html

(0)
上一篇 2025-05-05 10:00
下一篇 2025-05-05 10:00

相关推荐