linux

C++多线程在Linux中如何实现

小樊
36
2025-06-03 14:39:00
栏目: 编程语言

在Linux中,C++多线程可以通过POSIX线程库(pthread)来实现。以下是一个简单的示例,展示了如何在C++中使用pthread创建和管理线程:

  1. 首先,确保你的系统已经安装了pthread库。在大多数Linux发行版中,它已经是默认安装的。

  2. 创建一个名为thread_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;
        int result = pthread_create(&threads[i], nullptr, thread_function, &thread_ids[i]);
        if (result != 0) {
            std::cerr << "创建线程失败,错误代码:" << result << 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++编译器编译代码:
g++ -o thread_example thread_example.cpp -pthread

注意:在编译命令中添加-pthread参数,以便链接pthread库。

  1. 运行程序:
./thread_example

这个示例将创建5个线程,每个线程都会打印其线程ID。主线程会等待所有子线程完成后才退出。

在实际应用中,你可能需要使用互斥锁(mutex)、条件变量(condition variable)等同步原语来确保线程安全。这些同步原语也可以在pthread库中找到。

0
看了该问题的人还看了