自己写的CONDITION_VARIABLE和SRWLock配合使用的例子

时间:2021-10-15 18:22:06

        其中先启动TimeTrigger线程,用的是排他锁,另外两个线程用的是共享锁,可以并发。整体来看就是TimeTrigger完后,Thread1和Thread2并发一次。主要在于用一个线程控制另外多个线程的并发,尝试开设线程之间地位不平等时,线程的并发处理,如果加锁加的好的话,是可以达到效果的。

// Test.cpp : Defines the entry point for the console application.

//

 

#include "stdafx.h"

#include <windows.h>

#include <stdio.h>

 

CONDITION_VARIABLE cv;

SRWLOCK slock;

 

DWORD WINAPI TimeTrigger(LPVOID)

{

    while(true)

    {

        Sleep(2);

        AcquireSRWLockExclusive(&slock);

        Sleep(20);

        ReleaseSRWLockExclusive(&slock);

        WakeAllConditionVariable(&cv);

    }

}

 

 

DWORD WINAPI Thread1(LPVOID)

{

    int a  = 0;

    while(true)

    {

        AcquireSRWLockShared(&slock);

        SleepConditionVariableSRW(&cv,&slock,INFINITE,CONDITION_VARIABLE_LOCKMODE_SHARED);

        a++;

        printf("thread1:  a = %d\n",a);

        ReleaseSRWLockShared(&slock);

    }

}

 

DWORD WINAPI Thread2(LPVOID)

{

    int b = 0;

    while(true)

    {

        AcquireSRWLockShared(&slock);

        SleepConditionVariableSRW(&cv,&slock,INFINITE,CONDITION_VARIABLE_LOCKMODE_SHARED);

        b++;

        printf("thread2:  b = %d\n",b);

        ReleaseSRWLockShared(&slock);

    }

}

 

 

 

 

int _tmain(int argc, _TCHAR* argv[])

{

    InitializeSRWLock(&slock);

    CreateThread(NULL,0,TimeTrigger,NULL,0,NULL);

    CreateThread(NULL,0,Thread1,NULL,0,NULL);

    CreateThread(NULL,0,Thread2,NULL,0,NULL);

    if(getchar())

    {

       

    };

    return 0;

}