温馨提示×

CentOS下C++并发如何处理

小樊
43
2025-10-02 20:56:30
栏目: 编程语言

在CentOS下使用C++进行并发编程,可以采用多种方法。以下是一些常见的并发处理方式:

  1. 多线程:使用C++11标准库中的<thread>头文件来创建和管理线程。这种方式简单易用,适合处理大量的并发任务。
#include <iostream>
#include <thread>

void helloFunction() {
    std::cout << "Hello from a thread!" << std::endl;
}

int main() {
    std::thread t(helloFunction);
    t.join(); // 等待线程完成
    return 0;
}
  1. 互斥锁:使用<mutex>头文件中的互斥锁(std::mutex)来保护共享资源,防止数据竞争。
#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx; // 创建一个互斥锁

void printMessage(const std::string& msg) {
    mtx.lock(); // 加锁
    std::cout << msg << std::endl;
    mtx.unlock(); // 解锁
}

int main() {
    std::thread t1(printMessage, "Hello from thread 1");
    std::thread t2(printMessage, "Hello from thread 2");

    t1.join();
    t2.join();

    return 0;
}
  1. 条件变量:使用<condition_variable>头文件中的条件变量(std::condition_variable)来实现线程间的同步。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void printId(int id) {
    std::unique_lock<std::mutex> lck(mtx);
    cv.wait(lck, []{return ready;}); // 等待条件变量
    std::cout << "Thread " << id << std::endl;
}

void go() {
    std::unique_lock<std::mutex> lck(mtx);
    ready = true;
    cv.notify_all(); // 通知所有等待的线程
}

int main() {
    std::thread threads[10];
    for (auto& th : threads) {
        th = std::thread(printId, &th - &threads[0]);
    }
    std::this_thread::sleep_for(std::chrono::seconds(1)); // 等待线程创建
    go(); // 启动线程
    for (auto& th : threads) {
        th.join();
    }
    return 0;
}
  1. 原子操作:使用<atomic>头文件中的原子类型(如std::atomic<int>)来进行线程安全的操作。
#include <iostream>
#include <thread>
#include <atomic>

std::atomic<int> counter(0);

void incrementCounter() {
    for (int i = 0; i < 1000; ++i) {
        counter.fetch_add(1); // 原子加法
    }
}

int main() {
    std::thread t1(incrementCounter);
    std::thread t2(incrementCounter);

    t1.join();
    t2.join();

    std::cout << "Counter: " << counter.load() << std::endl; // 输出计数器的值
    return 0;
}
  1. 信号量:虽然C++标准库中没有直接提供信号量的实现,但可以使用POSIX信号量(sem_t)来进行线程同步。
#include <iostream>
#include <thread>
#include <semaphore.h>

sem_t sem;

void printMessage(const std::string& msg) {
    sem_wait(&sem); // 等待信号量
    std::cout << msg << std::endl;
    sem_post(&sem); // 发送信号量
}

int main() {
    sem_init(&sem, 0, 1); // 初始化信号量,初始值为1

    std::thread t1(printMessage, "Hello from thread 1");
    std::thread t2(printMessage, "Hello from thread 2");

    t1.join();
    t2.join();

    sem_destroy(&sem); // 销毁信号量
    return 0;
}
  1. 异步编程:使用C++11标准库中的<future><async>头文件来进行异步编程。
#include <iostream>
#include <future>

int add(int x, int y) {
    return x + y;
}

int main() {
    auto result = std::async(std::launch::async, add, 5, 7); // 异步执行add函数
    std::cout << "The result is " << result.get() << std::endl; // 获取异步操作的结果
    return 0;
}

在使用这些并发编程技术时,需要注意线程安全问题,合理使用同步机制来避免数据竞争和其他并发问题。此外,还需要考虑线程的创建和销毁开销,以及线程间的通信和同步开销。

0