温馨提示×

Linux C++多线程同步方法

小樊
38
2025-11-23 07:10:49
栏目: 编程语言

在Linux环境下使用C++进行多线程编程时,线程同步是一个重要的问题。以下是一些常用的线程同步方法:

1. 互斥锁(Mutex)

互斥锁是最基本的同步机制,用于保护共享资源,防止多个线程同时访问。

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

std::mutex mtx;
int shared_data = 0;

void increment() {
    mtx.lock();
    ++shared_data;
    mtx.unlock();
}

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

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

    std::cout << "Shared data: " << shared_data << std::endl;
    return 0;
}

2. 递归互斥锁(Recursive Mutex)

递归互斥锁允许同一个线程多次锁定同一个互斥锁,而不会导致死锁。

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

std::recursive_mutex mtx;
int shared_data = 0;

void increment(int count) {
    if (count <= 0) return;
    mtx.lock();
    ++shared_data;
    increment(count - 1);
    mtx.unlock();
}

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

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

    std::cout << "Shared data: " << shared_data << std::endl;
    return 0;
}

3. 条件变量(Condition Variable)

条件变量用于线程间的等待和通知机制。

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

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

void worker() {
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, []{ return ready; });
    std::cout << "Worker thread is processing data\n";
}

void trigger() {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::lock_guard<std::mutex> lock(mtx);
    ready = true;
    cv.notify_one();
}

int main() {
    std::thread t1(worker);
    std::thread t2(trigger);

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

    return 0;
}

4. 信号量(Semaphore)

信号量是一种计数器,用于控制对共享资源的访问。

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

std::binary_semaphore sem(0);
int shared_data = 0;

void producer() {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    ++shared_data;
    sem.release();
}

void consumer() {
    sem.acquire();
    std::cout << "Consumed data: " << shared_data << std::endl;
}

int main() {
    std::thread t1(producer);
    std::thread t2(consumer);

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

    return 0;
}

5. 原子操作(Atomic Operations)

原子操作可以在不使用锁的情况下实现线程安全的操作。

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

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

void increment() {
    ++shared_data;
}

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

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

    std::cout << "Shared data: " << shared_data << std::endl;
    return 0;
}

总结

选择合适的同步方法取决于具体的应用场景和需求。互斥锁和条件变量是最常用的同步机制,而原子操作则适用于简单的计数操作。在实际编程中,应尽量避免复杂的同步逻辑,以减少潜在的死锁和竞态条件。

0