centos

CentOS里C++多线程如何实现

小樊
44
2025-08-10 14:51:26
栏目: 编程语言

在CentOS系统中,使用C++实现多线程主要依赖于POSIX线程库(pthread)。以下是一个简单的示例,展示了如何在C++中使用pthread库创建和管理线程。

  1. 首先,确保你的CentOS系统已经安装了gcc编译器。如果没有,请运行以下命令安装:
sudo yum install gcc
  1. 创建一个名为multithread_example.cpp的文件,并输入以下代码:
#include <iostream>
#include <pthread.h>

// 线程函数
void* thread_function(void* arg) {
    int thread_id = *(static_cast<int*>(arg));
    std::cout << "线程 " << thread_id << " 正在运行" << std::endl;
    return nullptr;
}

int main() {
    const int num_threads = 5;
    pthread_t threads[num_threads];
    int thread_ids[num_threads];

    // 创建线程
    for (int i = 0; i < num_threads; ++i) {
        thread_ids[i] = i;
        if (pthread_create(&threads[i], nullptr, thread_function, &thread_ids[i])) {
            std::cerr << "创建线程失败" << std::endl;
            return 1;
        }
    }

    // 等待线程结束
    for (int i = 0; i < num_threads; ++i) {
        pthread_join(threads[i], nullptr);
    }

    std::cout << "所有线程已完成" << std::endl;
    return 0;
}
  1. 使用以下命令编译代码:
g++ -o multithread_example multithread_example.cpp -lpthread
  1. 运行生成的可执行文件:
./multithread_example

这个示例将创建5个线程,每个线程都会打印其线程ID。注意,在实际应用中,你可能需要使用互斥锁(mutex)或其他同步原语来确保线程安全地访问共享资源。

0
看了该问题的人还看了