linux

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

小樊
42
2025-05-14 09:36:10
栏目: 编程语言

在Linux中,C++程序可以通过多种方式实现多线程。以下是两种常用的方法:

方法一:使用POSIX线程(pthreads)

POSIX线程(pthreads)是一种广泛使用的多线程库,适用于Unix-like系统,包括Linux。

示例代码:

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

// 线程函数
void* thread_function(void* arg) {
    int thread_id = *(static_cast<int*>(arg));
    std::cout << "Thread " << thread_id << " is running." << 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]) != 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 finished." << std::endl;
    return 0;
}

编译和运行:

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

方法二:使用C++11标准库中的<thread>

C++11引入了标准库中的多线程支持,使用<thread>头文件可以更方便地实现多线程编程。

示例代码:

#include <iostream>
#include <thread>
#include <vector>

// 线程函数
void thread_function(int thread_id) {
    std::cout << "Thread " << thread_id << " is running." << std::endl;
}

int main() {
    const int num_threads = 5;
    std::vector<std::thread> threads;

    // 创建线程
    for (int i = 0; i < num_threads; ++i) {
        threads.emplace_back(thread_function, i);
    }

    // 等待线程结束
    for (auto& t : threads) {
        t.join();
    }

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

编译和运行:

g++ -std=c++11 -pthread -o multithread_example multithread_example.cpp
./multithread_example

总结

选择哪种方法取决于你的具体需求和项目环境。

0
看了该问题的人还看了