在Linux环境下使用C++进行并发编程,主要有以下几种方式:
POSIX Threads(简称pthreads)是C语言的一个标准线程库,也可以在C++中使用。
#include <pthread.h>void*,参数为void*。pthread_create函数。pthread_join函数。pthread_exit函数。#include <iostream>
#include <pthread.h>
void* threadFunction(void* arg) {
    std::cout << "Thread is running" << std::endl;
    pthread_exit(nullptr);
}
int main() {
    pthread_t thread;
    int result = pthread_create(&thread, nullptr, threadFunction, nullptr);
    if (result != 0) {
        std::cerr << "Error creating thread" << std::endl;
        return 1;
    }
    void* status;
    pthread_join(thread, &status);
    std::cout << "Thread has finished" << std::endl;
    return 0;
}
C++11引入了标准库线程支持,提供了更现代和类型安全的线程管理。
#include <thread>std::thread对象。join或detach方法。#include <iostream>
#include <thread>
void threadFunction() {
    std::cout << "Thread is running" << std::endl;
}
int main() {
    std::thread t(threadFunction);
    t.join(); // 等待线程结束
    std::cout << "Thread has finished" << std::endl;
    return 0;
}
std::async)std::async是C++11引入的另一种并发编程方式,它返回一个std::future对象,可以用来获取异步任务的结果。
#include <iostream>
#include <future>
int asyncFunction() {
    std::this_thread::sleep_for(std::chrono::seconds(2));
    return 42;
}
int main() {
    std::future<int> result = std::async(std::launch::async, asyncFunction);
    std::cout << "Waiting for the result..." << std::endl;
    int value = result.get(); // 获取结果
    std::cout << "Result is: " << value << std::endl;
    return 0;
}
C++标准库提供了一些并发容器和算法,如std::atomic、std::mutex、std::lock_guard等,用于实现线程安全的操作。
#include <iostream>
#include <thread>
#include <atomic>
std::atomic<int> counter(0);
void incrementCounter() {
    for (int i = 0; i < 100000; ++i) {
        counter++;
    }
}
int main() {
    std::thread t1(incrementCounter);
    std::thread t2(incrementCounter);
    t1.join();
    t2.join();
    std::cout << "Counter value: " << counter << std::endl;
    return 0;
}
std::async:适用于需要异步任务和结果获取的场景。选择哪种方式取决于具体的需求和应用场景。