溫馨提示×

Linux下C++多線程同步怎么做

小樊
82
2025-02-20 06:00:58
欄目: 編程語言

在Linux下使用C++進行多線程編程時,線程同步是一個重要的問題。以下是一些常用的線程同步機制:

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_id(int id) {
    std::unique_lock<std::mutex> lck(mtx);
    cv.wait(lck, []{return ready;}); // 等待條件變量
    std::cout << "Thread " << id << '\n';
}

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(print_id, i);

    std::cout << "10 threads ready to race...\n";
    go(); // go!

    for (auto &th : threads) th.join();

    return 0;
}

3. 信號量(Semaphore)

信號量是一種更高級的同步機制,可以用于控制對共享資源的訪問。

#include <iostream>
#include <thread>
#include <semaphore>

std::binary_semaphore sem(0); // 二進制信號量

void print_block(int n, char c) {
    sem.acquire(); // 等待信號量
    for (int i = 0; i < n; ++i) {
        std::cout << c;
    }
    std::cout << '\n';
}

void go() {
    std::this_thread::sleep_for(std::chrono::seconds(1)); // 模擬一些工作
    sem.release(); // 釋放信號量
}

int main() {
    std::thread th1(print_block, 50, '*');
    std::thread th2(print_block, 50, '$');

    std::thread t(go);

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

    return 0;
}

4. 原子操作(Atomic Operations)

原子操作可以在不使用鎖的情況下實現線程安全的操作。

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

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

void increment() {
    for (int i = 0; i < 100000; ++i) {
        counter.fetch_add(1, std::memory_order_relaxed);
    }
}

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

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

    std::cout << "Counter: " << counter.load() << '\n';

    return 0;
}

5. 屏障(Barrier)

屏障用于確保多個線程在某個點上同步。

#include <iostream>
#include <thread>
#include <barrier>

std::barrier bar(2); // 創建一個屏障,等待兩個線程

void print_hello() {
    std::cout << "Hello from thread " << std::this_thread::get_id() << '\n';
    bar.arrive_and_wait(); // 等待其他線程
    std::cout << "After barrier from thread " << std::this_thread::get_id() << '\n';
}

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

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

    return 0;
}

這些是Linux下C++多線程編程中常用的同步機制。根據具體的需求和場景,可以選擇合適的同步機制來實現線程間的協調和通信。

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