溫馨提示×

Linux C++程序怎樣實現并發控制

小樊
61
2025-03-17 01:29:00
欄目: 編程語言

在Linux環境下使用C++實現并發控制,可以采用多種方法。以下是一些常用的并發控制機制:

  1. 互斥鎖(Mutexes): 互斥鎖是最基本的同步機制,用于確保多個線程不會同時訪問共享資源。

    #include <mutex>
    #include <thread>
    
    std::mutex mtx; // 全局互斥鎖
    
    void print_block(int n, char c) {
        mtx.lock(); // 加鎖
        for (int i = 0; i < n; ++i) {
            std::cout << c;
        }
        std::cout << '\n';
        mtx.unlock(); // 解鎖
    }
    
    int main() {
        std::thread th1(print_block, 50, '*');
        std::thread th2(print_block, 50, '$');
    
        th1.join();
        th2.join();
    
        return 0;
    }
    
  2. 遞歸互斥鎖(Recursive Mutexes): 如果一個線程需要多次獲取同一個互斥鎖,可以使用遞歸互斥鎖。

    #include <mutex>
    #include <thread>
    
    std::recursive_mutex rmtx;
    
    void func(int n) {
        if (n <= 0) return;
        rmtx.lock();
        func(n - 1);
        rmtx.unlock();
    }
    
    int main() {
        std::thread t(func, 10);
        t.join();
        return 0;
    }
    
  3. 條件變量(Condition Variables): 條件變量允許線程等待某個條件成立,或者通知其他線程某個條件已經成立。

    #include <condition_variable>
    #include <mutex>
    #include <thread>
    #include <queue>
    
    std::mutex mtx;
    std::condition_variable cv;
    std::queue<int> q;
    
    void producer() {
        for (int i = 0; i < 10; ++i) {
            std::unique_lock<std::mutex> lock(mtx);
            q.push(i);
            cv.notify_one(); // 通知消費者
        }
    }
    
    void consumer() {
        while (true) {
            std::unique_lock<std::mutex> lock(mtx);
            cv.wait(lock, [] { return !q.empty(); }); // 等待直到隊列非空
            int val = q.front();
            q.pop();
            if (val == 9) break; // 如果收到最后一個值,退出循環
        }
    }
    
    int main() {
        std::thread prod(producer);
        std::thread cons(consumer);
    
        prod.join();
        cons.join();
    
        return 0;
    }
    
  4. 讀寫鎖(Read-Write Locks): 當共享資源讀取操作遠多于寫入操作時,使用讀寫鎖可以提高性能。

    #include <shared_mutex>
    #include <thread>
    
    std::shared_mutex rw_mtx;
    
    void read_func() {
        std::shared_lock<std::shared_mutex> lock(rw_mtx); // 共享鎖
        // 執行讀操作
    }
    
    void write_func() {
        std::unique_lock<std::shared_mutex> lock(rw_mtx); // 排他鎖
        // 執行寫操作
    }
    
    int main() {
        // 創建多個讀取線程和寫入線程
        return 0;
    }
    
  5. 原子操作(Atomic Operations): 對于簡單的數據類型,可以使用原子操作來避免鎖的開銷。

    #include <atomic>
    #include <thread>
    
    std::atomic<int> counter(0);
    
    void increment_counter() {
        for (int i = 0; i < 1000; ++i) {
            counter.fetch_add(1, std::memory_order_relaxed);
        }
    }
    
    int main() {
        std::thread t1(increment_counter);
        std::thread t2(increment_counter);
    
        t1.join();
        t2.join();
    
        std::cout << "Counter: " << counter.load() << '\n';
    
        return 0;
    }
    
  6. 信號量(Semaphores): 信號量是一種更高級的同步機制,可以用來控制對共享資源的訪問。

    #include <semaphore>
    #include <thread>
    
    std::binary_semaphore sem(1); // 二進制信號量
    
    void critical_section() {
        sem.acquire(); // 獲取資源
        // 執行關鍵區代碼
        sem.release(); // 釋放資源
    }
    
    int main() {
        std::thread t1(critical_section);
        std::thread t2(critical_section);
    
        t1.join();
        t2.join();
    
        return 0;
    }
    

在使用這些并發控制機制時,需要注意避免死鎖和其他同步問題。合理地設計程序結構和鎖的使用策略對于編寫高效且安全的并發程序至關重要。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女