温馨提示×

C++如何在Linux中实现并发

小樊
43
2025-12-22 20:39:37
栏目: 编程语言

在Linux中,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>库中的互斥锁。
#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>库可以在多线程之间同步状态。
#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::lock_guard<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>库可以执行无锁的并发操作。
#include <iostream>
#include <thread>
#include <atomic>

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

void incrementCounter() {
    for (int i = 0; i < 100000; ++i) {
        counter.fetch_add(1, std::memory_order_relaxed); // 原子加法
    }
}

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

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

    std::cout << "Counter: " << counter.load() << std::endl; // 输出计数器的值

    return 0;
}
  1. 异步编程:使用<future><async>库可以异步地执行任务并获取结果。
#include <iostream>
#include <future>

int calculateSum(int a, int b) {
    return a + b;
}

int main() {
    auto future = std::async(std::launch::async, calculateSum, 5, 7); // 异步执行
    std::cout << "Waiting for result..." << std::endl;
    int sum = future.get(); // 获取结果
    std::cout << "The sum is: " << sum << std::endl;

    return 0;
}
  1. 信号量:虽然C++标准库没有直接提供信号量的支持,但可以使用POSIX信号量(semaphore.h)。
#include <iostream>
#include <thread>
#include <semaphore.h>

sem_t sem;

void workerThread() {
    sem_wait(&sem); // 等待信号量
    std::cout << "Worker thread is processing..." << std::endl;
    sem_post(&sem); // 发送信号量
}

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

    std::thread t(workerThread);

    std::this_thread::sleep_for(std::chrono::seconds(1)); // 等待一段时间
    sem_post(&sem); // 发送信号量,允许工作线程继续

    t.join();
    sem_destroy(&sem); // 销毁信号量

    return 0;
}

这些是C++在Linux中实现并发的一些基本方法。在实际应用中,可能需要结合使用这些方法来满足特定的并发需求。

0