读写锁 C++11

该文章介绍了如何使用C++实现一个进阶版的读写锁,包括读锁和写锁的管理。读锁使用了共享互斥锁(shared_mutex),在读写冲突时利用条件变量进行协调。在读写计数和状态管理上,文章详细展示了锁的获取和释放过程。
摘要由CSDN通过智能技术生成
#include <shared_mutex>

class readWriteLock {
private:
    std::shared_mutex readMtx;
    std::mutex writeMtx;
    int readCnt; // 已加读锁个数
public:
    readWriteLock() : readCnt(0) {}
    void readLock()
    {
        readMtx.lock();
        if (++readCnt == 1) {
            writeMtx.lock();  // 存在线程读操作时,写加锁(只加一次)
        }
        readMtx.unlock();
    }
    void readUnlock()
    {
        readMtx.lock();
        if (--readCnt == 0) { // 没有线程读操作时,释放写锁
            writeMtx.unlock();
        }
        readMtx.unlock();
    }
    void writeLock()
    {
        writeMtx.lock();
    }
    void writeUnlock()
    {
        writeMtx.unlock();
    }
};

进阶版

#pragma once

#include <mutex>
#include <condition_variable>

namespace zone
{
    class read_write_mutex
    {
    public:
        read_write_mutex() = default;
        ~read_write_mutex() = default;

        read_write_mutex(const read_write_mutex &) = delete;
        read_write_mutex & operator=(const read_write_mutex &) = delete;

        read_write_mutex(const read_write_mutex &&) = delete;
        read_write_mutex & operator=(const read_write_mutex &&) = delete;

        void lock_read() {
            std::unique_lock<std::mutex> lock( m_mutex );
            m_cond_read.wait(lock, [this]()-> bool {
                    return m_write_count == 0;
                });
            ++m_read_count;
        }

        void unlock_read() {
            std::unique_lock<std::mutex> lock( m_mutex );
            if (--m_read_count == 0 && m_write_count > 0) {
                m_cond_write.notify_one();
            }
        }

        void lock_write() {
            std::unique_lock<std::mutex> lock( m_mutex );
            ++m_write_count;
            m_cond_write.wait(lock, [this]()-> bool {
                    return m_read_count == 0 && !m_writing;
                });
            m_writing = true;
        }

        void unlock_write() {
            std::unique_lock<std::mutex> lock( m_mutex );
            if (--m_write_count == 0) {
                m_cond_read.notify_all();
            } else {
                m_cond_write.notify_one();
            }
            m_writing = false;
        }

    private:
        volatile size_t m_read_count = 0;
        volatile size_t m_write_count = 0;
        volatile bool m_writing = false;
        std::mutex m_mutex;
        std::condition_variable m_cond_read;
        std::condition_variable m_cond_write;
    };

C11标准中提供了读写锁(read-write lock)的机制,可以在多线程环境下实现对共享资源的读写控制。读写锁可以分为读锁和写锁,读锁可以被多个线程同时持有,但是写锁只能被一个线程独占。读写锁的基本操作包括: 1. 初始化:pthread_rwlock_init() 2. 加读锁:pthread_rwlock_rdlock() 3. 加写锁:pthread_rwlock_wrlock() 4. 解锁:pthread_rwlock_unlock() 5. 销毁:pthread_rwlock_destroy() 下面是一个简单的使用读写锁的例子: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> pthread_rwlock_t rwlock; int shared_data = 0; void *reader(void *arg) { pthread_rwlock_rdlock(&rwlock); printf("Reader %ld: shared_data = %d\n", (long)arg, shared_data); pthread_rwlock_unlock(&rwlock); return NULL; } void *writer(void *arg) { pthread_rwlock_wrlock(&rwlock); shared_data++; printf("Writer %ld: shared_data = %d\n", (long)arg, shared_data); pthread_rwlock_unlock(&rwlock); return NULL; } int main() { pthread_t threads[6]; pthread_rwlock_init(&rwlock, NULL); for (long i = 0; i < 2; i++) { pthread_create(&threads[i], NULL, writer, (void *)i); } for (long i = 2; i < 6; i++) { pthread_create(&threads[i], NULL, reader, (void *)i); } for (int i = 0; i < 6; i++) { pthread_join(threads[i], NULL); } pthread_rwlock_destroy(&rwlock); return 0; } ``` 在这个例子中,共有两个写线程和四个读线程。写线程负责增加共享数据的值,读线程负责读取共享数据的值。在写线程加写锁的时候,读线程会被阻塞;在读线程加读锁的时候,其他读线程可以同时持有读锁,但是写线程会被阻塞。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值