linux

如何在Linux用C++实现并发控制

小樊
41
2025-11-15 08:26:24
栏目: 编程语言

在Linux环境下使用C++实现并发控制,通常会涉及到多线程编程。C++11标准库提供了对多线程的支持,包括线程的创建、同步和销毁等。以下是一些基本的步骤和示例代码,用于展示如何在Linux中使用C++实现并发控制。

  1. 包含必要的头文件

    #include <iostream>
    #include <thread>
    #include <mutex>
    #include <vector>
    
  2. 创建线程: 使用std::thread类来创建线程。

    void helloFunction() {
        std::cout << "Hello from a thread!" << std::endl;
    }
    
    int main() {
        std::thread t(helloFunction);
        t.join(); // 等待线程完成
        return 0;
    }
    
  3. 线程同步: 使用std::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;
    }
    
  4. 条件变量: 使用std::condition_variable来实现线程间的通信。

    #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;}); // 等待直到ready为true
        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;
    }
    
  5. 原子操作: 使用std::atomic来实现无锁的并发控制。

    #include <atomic>
    
    std::atomic<int> sharedValue(0);
    
    void incrementValue() {
        for (int i = 0; i < 1000; ++i) {
            sharedValue.fetch_add(1, std::memory_order_relaxed);
        }
    }
    
    int main() {
        std::thread t1(incrementValue);
        std::thread t2(incrementValue);
    
        t1.join();
        t2.join();
    
        std::cout << "Shared value: " << sharedValue.load() << std::endl;
    
        return 0;
    }
    

在Linux环境下编译C++多线程程序时,需要链接pthread库,可以使用以下命令:

g++ -std=c++11 -pthread your_program.cpp -o your_program

以上代码示例展示了如何在Linux中使用C++进行基本的并发控制。在实际应用中,可能需要根据具体情况选择合适的同步机制,并注意避免死锁和其他并发问题。

0
看了该问题的人还看了