温馨提示×

如何在Linux用C++处理并发

小樊
47
2025-10-27 10:46:38
栏目: 编程语言

在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); // 创建一个新线程来执行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];
    // spawn 10 threads:
    for (int i = 0; i < 10; ++i)
        threads[i] = std::thread(printId, i);

    std::cout << "10 threads ready to race..." << std::endl;
    go(); // 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 < 1000; ++i) {
        counter++; // 原子操作
    }
}

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

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

    std::cout << "Counter: " << counter << std::endl;

    return 0;
}
  1. 异步编程:使用<future><async>来执行异步任务。
#include <iostream>
#include <future>

int asyncFunction() {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    return 42;
}

int main() {
    std::future<int> result = std::async(std::launch::async, asyncFunction); // 异步执行函数

    std::cout << "Waiting for the result..." << std::endl;
    int sum = result.get(); // 获取异步操作的结果
    std::cout << "Result: " << sum << std::endl;

    return 0;
}
  1. 信号量:使用POSIX信号量(<semaphore.h>)或者System V信号量来控制对共享资源的访问。

  2. 管道和消息队列:使用UNIX域套接字或者管道(<pipe.h>)来实现进程间通信。

  3. 共享内存:使用POSIX共享内存(<sys/mman.h>)或者System V共享内存(<sys/shm.h>)来在进程间共享数据。

选择合适的并发模型取决于具体的应用场景和性能需求。在实际编程中,可能需要结合使用这些技术来实现高效且安全的并发控制。

0