溫馨提示×

linux c++多線程如何同步

c++
小樊
130
2024-12-03 23:58:41
欄目: 編程語言

在Linux環境下使用C++多線程時,同步是一個重要的問題,以確保數據的一致性和線程安全。C++提供了多種同步機制,包括互斥鎖(mutex)、條件變量(condition variable)、讀寫鎖(reader-writer lock)等。以下是一些常見的同步方法:

1. 互斥鎖(Mutex)

互斥鎖是最基本的同步機制,用于保護共享資源不被多個線程同時訪問。

#include <iostream>
#include <thread>
#include <mutex>

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. 條件變量(Condition Variable)

條件變量用于線程間的通信,允許一個線程等待某個條件成立。

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

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

void print_ready_message() {
    std::unique_lock<std::mutex> lck(mtx);
    while (!ready) { // 如果ready為false,則等待
        cv.wait(lck);
    }
    std::cout << "Ready!\n";
}

void set_ready() {
    std::lock_guard<std::mutex> lck(mtx);
    ready = true;
    cv.notify_one(); // 喚醒等待的線程
}

int main() {
    std::thread th1(print_ready_message);
    std::thread th2(set_ready);

    th1.join();
    th2.join();

    return 0;
}

3. 讀寫鎖(Reader-Writer Lock)

讀寫鎖允許多個線程同時讀取共享資源,但只允許一個線程寫入。

#include <iostream>
#include <thread>
#include <shared_mutex>
#include <vector>

std::shared_mutex rw_mtx; // 讀寫鎖
int data = 0;

void read_data() {
    std::shared_lock<std::shared_mutex> lock(rw_mtx);
    std::cout << "Read: " << data << '\n';
}

void write_data(int value) {
    std::unique_lock<std::shared_mutex> lock(rw_mtx);
    data = value;
    std::cout << "Write: " << data << '\n';
}

int main() {
    std::thread th1(read_data);
    std::thread th2(write_data, 42);
    std::thread th3(read_data);

    th1.join();
    th2.join();
    th3.join();

    return 0;
}

4. 原子操作(Atomic Operations)

原子操作是不可中斷的操作,用于簡單的同步需求。

#include <iostream>
#include <thread>
#include <atomic>

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

void increment() {
    for (int i = 0; i < 1000; ++i) {
        ++counter;
    }
}

int main() {
    std::thread th1(increment);
    std::thread th2(increment);

    th1.join();
    th2.join();

    std::cout << "Counter: " << counter << '\n';

    return 0;
}

總結

選擇合適的同步機制取決于具體的應用場景和需求?;コ怄i適用于簡單的保護共享資源,條件變量適用于線程間的通信,讀寫鎖適用于讀多寫少的場景,原子操作適用于簡單的計數器等場景。在實際編程中,應根據具體情況選擇合適的同步方法,以確保線程安全和數據一致性。

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