溫馨提示×

C++ Linux編程如何處理多線程同步

小樊
37
2025-05-20 11:26:44
欄目: 編程語言

在C++ Linux編程中,處理多線程同步通常涉及使用互斥鎖(mutexes)、條件變量(condition variables)、信號量(semaphores)和原子操作(atomic operations)等機制。以下是一些常用的同步方法:

  1. 互斥鎖(mutexes): 互斥鎖用于確保多個線程不會同時訪問共享資源。在C++11中,可以使用std::mutex來實現互斥鎖。
#include <iostream>
#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;
}
  1. 條件變量(condition variables): 條件變量允許線程在某個條件滿足時等待,并在條件改變時被喚醒。在C++11中,可以使用std::condition_variable來實現條件變量。
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>

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::unique_lock<std::mutex> lck(mtx);
    ready = true;
    cv.notify_all();
}

int main() {
    std::thread threads[10];
    for (int i = 0; i < 10; ++i) {
        threads[i] = std::thread(print_id, i);
    }

    std::this_thread::sleep_for(std::chrono::seconds(1));
    go();

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

    return 0;
}
  1. 信號量(semaphores): 信號量是一種計數器,用于控制多個線程對共享資源的訪問。在Linux系統中,可以使用sem_t結構體和相關的函數來實現信號量。
#include <iostream>
#include <semaphore.h>
#include <thread>

sem_t sem;

void print_block(int n, char c) {
    sem_wait(&sem);
    for (int i = 0; i < n; ++i) {
        std::cout << c;
    }
    std::cout << '\n';
    sem_post(&sem);
}

int main() {
    sem_init(&sem, 0, 1);

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

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

    sem_destroy(&sem);

    return 0;
}
  1. 原子操作(atomic operations): 原子操作是一種不可中斷的操作,可以確保多個線程在訪問共享資源時不會發生沖突。在C++11中,可以使用std::atomic模板類來實現原子操作。
#include <iostream>
#include <atomic>
#include <thread>

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

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

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

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

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

    return 0;
}

這些同步方法可以根據實際需求進行選擇和組合,以實現多線程之間的同步。

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