C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > C++ 各种锁

示例详解C++中的各种锁

作者:Arthurian

C++中常见的锁包括互斥锁、递归互斥锁、读写锁、定时互斥锁、递归定时互斥锁、自旋锁和条件变量,互斥锁用于防止多线程同时访问共享资源,递归互斥锁允许同一线程多次获取锁,读写锁区分读写操作,提高并发性

在多线程开发中,经常会遇到数据同步,很多情况下用锁都是一个很好的选择。C++中常用的锁主要有下面几种:

互斥锁(std::mutex)

#include <iostream>
#include <mutex>
#include <thread>
std::mutex m;
int counter = 0;
void increment() {
    m.lock();
    counter++;
    std::cout << "Counter value in thread " << std::this_thread::get_id() << " is " << counter << std::endl;
    m.unlock();
}
int main() {
    std::thread t1(increment);
    std::thread t2(increment);
    t1.join();
    t2.join();
    return 0;
}

递归互斥锁(std::recursive_mutex)

#include <iostream>
#include <mutex>
#include <thread>
std::recursive_mutex rm;
void recursiveFunction(int count) {
    rm.lock();
    if (count > 0) {
        std::cout << "Recursive call with count = " << count << std::endl;
        recursiveFunction(count - 1);
    }
    rm.unlock();
}
int main() {
    std::thread t(recursiveFunction, 3);
    t.join();
    return 0;
}

读写锁(std::shared_mutex) C++17开始才有

#include <iostream>
#include <shared_mutex>
#include <thread>
#include <vector>
std::shared_mutex smtx;
int shared_data = 0;
void read_data() {
    std::shared_lock<std::shared_mutex> lock(smtx);
    std::cout << "Read data: " << shared_data << std::endl;
}
void write_data(int new_value) {
    std::unique_lock<std::shared_mutex> lock(smtx);
    shared_data = new_value;
    std::cout << "Wrote data: " << shared_data << std::endl;
}
int main() {
    std::vector<std::thread> read_threads;
    for (int i = 0; i < 5; i++) {
        read_threads.push_back(std::thread(read_data));
    }
    std::thread write_thread(write_data, 10);
    for (auto& t : read_threads) {
        t.join();
    }
    write_thread.join();
    return 0;
}

定时互斥锁(std::timed_mutex)

#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
std::timed_mutex tm;
void tryLockFunction() {
    if (tm.try_lock_for(std::chrono::seconds(1))) {
        std::cout << "Acquired lock" << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(2));
        tm.unlock();
    } else {
        std::cout << "Could not acquire lock in time" << std::endl;
    }
}
int main() {
    std::thread t1(tryLockFunction);
    std::thread t2(tryLockFunction);
    t1.join();
    t2.join();
    return 0;
}

递归定时互斥锁(std::recursive_timed_mutex)

#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
std::recursive_timed_mutex rtm;
void recursiveTryLockFunction(int count) {
    if (rtm.try_lock_for(std::chrono::seconds(1))) {
        std::cout << "Recursive acquired lock, count = " << count << std::endl;
        if (count > 0) {
            recursiveTryLockFunction(count - 1);
        }
        rtm.unlock();
    } else {
        std::cout << "Could not recursively acquire lock in time" << std::endl;
    }
}
int main() {
    std::thread t(recursiveTryLockFunction, 3);
    t.join();
    return 0;
}

自旋锁(通常用std::atomic_flag实现)

#include <iostream>
#include <atomic>
#include <thread>
std::atomic_flag spinLock = ATOMIC_FLAG_INIT;
void criticalSection() {
    while (spinLock.test_and_set()) {
        // 自旋等待
    }
    std::cout << "Entered critical section" << std::endl;
    // 临界区操作
    spinLock.clear();
}
int main() {
    std::thread t1(criticalSection);
    std::thread t2(criticalSection);
    t1.join();
    t2.join();
    return 0;
}

条件变量(std::condition_variable)配合互斥锁用于同步(严格来说条件变量不是锁,但常一起用于线程同步场景)

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
std::mutex mtx;
std::condition_variable cv;
std::queue<int> buffer;
const int bufferSize = 5;
void producer() {
    for (int i = 0; i < 10; ++i) {
        std::unique_lock<std::mutex> lock(mtx);
        while (buffer.size() == bufferSize) {
            cv.wait(lock);
        }
        buffer.push(i);
        std::cout << "Produced: " << i << std::endl;
        cv.notify_all();
    }
}
void consumer() {
    for (int i = 0; i < 10; ++i) {
        std::unique_lock<std::mutex> lock(mtx);
        while (buffer.empty()) {
            cv.wait(lock);
        }
        int data = buffer.front();
        buffer.pop();
        std::cout << "Consumed: " << data << std::endl;
        cv.notify_all();
    }
}
int main() {
    std::thread producerThread(producer);
    std::thread consumerThread(consumer);
    producerThread.join();
    consumerThread.join();
    return 0;
}

到此这篇关于C++中的各种锁的文章就介绍到这了,更多相关C++ 各种锁内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文