美文网首页
slim 读写锁

slim 读写锁

作者: 7bfedbe4863a | 来源:发表于2017-12-31 10:33 被阅读0次

分配一个SRWLOCK 结构并初始化

SRWLOCK srwLock;
VOID InitializeSRWLock(&srwLock);

写入者线程独占锁

获得独占访问权:
VOID AcquireSRWLockExclusive(&srwLock);
解除对资源的锁定:
VOID ReleaseSRWLockExclusive(&srwLock);

读取者共享

获取访问权限(非独占)
VOID AcquireSRWLockShared(&srwLock);
解除锁定
VOID ReleaseSRWLockShared(&srwLock);

-如果在锁被占用的时候,调用AcquireSRWLock*的时候会阻塞(调用线程
)。
-不能递归地获得SRWLOCK。

*具体代码和关键段类似。

SRWLOCK srwLock;
int dwData = 0;
unsigned __stdcall ThreadFuncRead(void* pIndex)
{
    unsigned temp = (unsigned)pIndex;
    int a = 0;
    while(1)
    {
        a++;
        AcquireSRWLockShared(&srwLock);
        printf("[%d]thread %d read:%d\n",a,temp,dwData);
        Sleep(1000);
        ReleaseSRWLockShared(&srwLock);
    }
    return 1;
}
unsigned __stdcall ThreadFuncWrite(void*)
{
    while (1)
    {
        AcquireSRWLockExclusive(&srwLock);
        dwData++;
        printf("Write %d\n",dwData);
        Sleep(800);
        ReleaseSRWLockExclusive(&srwLock);
    }
    return 1;
}
BOOL OnActive()
{
    InitializeSRWLock(&srwLock);

    int i=0;
    HANDLE hThreadRead[3];
    HANDLE hThreadWrite;
    unsigned uiThreadReadID[3]; 
    unsigned uiThreadWriteID;

    hThreadWrite = (HANDLE)_beginthreadex(NULL,0,ThreadFuncWrite,0,CREATE_SUSPENDED,&uiThreadWriteID);

    for (i=0;i<3;i++)
    {
        hThreadRead[i] = (HANDLE)_beginthreadex(NULL,0,ThreadFuncRead,(void*)i,CREATE_SUSPENDED,&(uiThreadReadID[i]));
    }

    ResumeThread(hThreadWrite);
    ResumeThread(hThreadRead[0]);
    ResumeThread(hThreadRead[1]);
    ResumeThread(hThreadRead[2]);

    Sleep(5000);

    CloseHandle(hThreadWrite);
    CloseHandle(hThreadRead[0]);
    CloseHandle(hThreadRead[1]);
    CloseHandle(hThreadRead[2]);

    return TRUE;
}

相关文章

  • slim 读写锁

    分配一个SRWLOCK 结构并初始化 SRWLOCK srwLock;VOID InitializeSRWLock...

  • T480指纹识别支持

    目标 通过指纹识别解锁slim-lock 环境 操作系统archlinux 桌面管理器slim 锁屏slimloc...

  • 读写锁和互斥锁 读写互斥锁,简称读写锁 mux sync.RWMutex Lock和Unlock分别对写锁进行锁定...

  • 线程同步(下)

    继上篇。这篇介绍的几种使用的较少。 读写锁 读写锁与互斥锁类似。不过读写锁允许更高的并行性。读写锁可以有三种状态:...

  • 可重入读写锁 ReentrantReadWriteLock

    读写锁分为读锁和写锁,多个线程获取读锁不互斥,读写锁、写写锁互斥。 输出

  • Java并发编程-读写锁(ReentrantReadWriteL

    章节目录 ReentrantReadWriteLock 特性 读写锁接口示例 读写锁的实现分析读写状态设计写锁的释...

  • 线程安全之读写锁

    相关API 初始化读写锁 释放读写锁 获取读锁 获取写锁 解锁 实例

  • ReadWriteLock读写锁

    1、引入ReadWriteLock读写锁 ReadWriteLock是JDK5中提供的读写分离锁。读写分离锁可以有...

  • 基于CAS的一些锁(5)- ReadWriteLock

    ReadWriteLock 读写锁。读写锁的概念其实就是共享锁和排他锁,读锁就是共享锁,写锁就是排他锁。 如何理解...

  • Go 语言的锁

    Go 语言提供两类锁: 互斥锁(Mutex)和读写锁(RWMutex)。其中读写锁(RWMutex)是基于互斥锁(...

网友评论

      本文标题:slim 读写锁

      本文链接:https://www.haomeiwen.com/subject/wdmogxtx.html