温馨提示×

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

小樊
52
2025-08-22 04:46:26
栏目: 编程语言

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

1. 包含必要的头文件

首先,你需要包含<pthread.h>头文件。

#include <iostream>
#include <pthread.h>

2. 定义线程函数

线程函数是每个线程将要执行的函数。它必须符合void* thread_function(void*)的签名。

void* thread_function(void* arg) {
    int thread_id = *(static_cast<int*>(arg));
    std::cout << "Thread " << thread_id << " is running." << std::endl;
    return nullptr;
}

3. 创建线程

使用pthread_create函数来创建线程。你需要传递线程函数的指针、线程参数和一个指向线程ID的指针。

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]) != 0) {
            std::cerr << "Failed to create thread "<< i << std::endl;
            return 1;
        }
    }

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

    std::cout << "All threads have completed." << std::endl;
    return 0;
}

4. 编译和运行

使用g++编译器来编译你的程序,并链接pthread库。

g++ -pthread -o multithread_example multithread_example.cpp
./multithread_example

解释

  • pthread_create函数用于创建线程。它的第一个参数是指向线程标识符的指针,第二个参数是指向线程属性的指针(通常设置为nullptr),第三个参数是线程函数的指针,第四个参数是传递给线程函数的参数。
  • pthread_join函数用于等待线程完成。它的第一个参数是线程标识符,第二个参数是指向返回值的指针(通常设置为nullptr)。

通过这种方式,你可以在Linux下使用C++实现多线程编程。

0