温馨提示×

C++在Linux中的多线程实现

小樊
44
2025-12-24 19:53:01
栏目: 编程语言

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

1. POSIX Threads (pthreads)

POSIX Threads(pthreads)是Linux和其他类Unix系统上实现多线程的标准API。

基本步骤:

  1. 包含头文件

    #include <pthread.h>
    
  2. 定义线程函数

    void* thread_function(void* arg) {
        // 线程执行的代码
        return nullptr;
    }
    
  3. 创建线程

    pthread_t thread_id;
    int result = pthread_create(&thread_id, nullptr, thread_function, nullptr);
    if (result != 0) {
        // 处理错误
    }
    
  4. 等待线程结束

    pthread_join(thread_id, nullptr);
    

示例代码:

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

void* thread_function(void* arg) {
    std::cout << "Thread is running" << std::endl;
    return nullptr;
}

int main() {
    pthread_t thread_id;
    int result = pthread_create(&thread_id, nullptr, thread_function, nullptr);
    if (result != 0) {
        std::cerr << "Error creating thread: " << result << std::endl;
        return 1;
    }

    pthread_join(thread_id, nullptr);
    std::cout << "Thread finished" << std::endl;
    return 0;
}

2. C++11 标准库线程

C++11引入了标准库中的线程支持,提供了更现代和类型安全的接口。

基本步骤:

  1. 包含头文件

    #include <thread>
    
  2. 定义线程函数

    void thread_function() {
        // 线程执行的代码
    }
    
  3. 创建线程

    std::thread thread(thread_function);
    
  4. 等待线程结束

    thread.join();
    

示例代码:

#include <iostream>
#include <thread>

void thread_function() {
    std::cout << "Thread is running" << std::endl;
}

int main() {
    std::thread thread(thread_function);
    thread.join();
    std::cout << "Thread finished" << std::endl;
    return 0;
}

3. C++20 协程

C++20引入了协程,提供了一种更高级的并发编程模型。

基本步骤:

  1. 包含头文件

    #include <coroutine>
    
  2. 定义协程类型

    struct Task {
        struct promise_type {
            Task get_return_object() { return {}; }
            std::suspend_never initial_suspend() { return {}; }
            std::suspend_never final_suspend() noexcept { return {}; }
            void return_void() {}
            void unhandled_exception() {}
        };
    };
    
  3. 使用协程

    Task async_function() {
        co_await std::suspend_never{};
        // 协程执行的代码
    }
    

示例代码:

#include <iostream>
#include <coroutine>

struct Task {
    struct promise_type {
        Task get_return_object() { return {}; }
        std::suspend_never initial_suspend() { return {}; }
        std::suspend_never final_suspend() noexcept { return {}; }
        void return_void() {}
        void unhandled_exception() {}
    };
};

Task async_function() {
    std::cout << "Coroutine is running" << std::endl;
    co_await std::suspend_never{};
}

int main() {
    async_function();
    std::cout << "Coroutine finished" << std::endl;
    return 0;
}

总结

  • pthreads:适用于需要与C代码兼容的场景,提供了底层的线程控制。
  • C++11 标准库线程:提供了更现代和类型安全的接口,适用于大多数C++程序。
  • C++20 协程:提供了更高级的并发编程模型,适用于需要异步编程的场景。

选择哪种方法取决于具体的需求和项目的复杂性。

0