#include"stdafx.h"
#include<windows.h>
#include<tchar.h>
#include<vector>
#include<iostream>
#include<process.h>
using namespace std;
DWORD WINAPI ThreadProduce(PVOID pvParam);
DWORD WINAPI ThreadUser1(PVOID pvParam);
DWORD WINAPI ThreadUser2(PVOID pvParam);
vector<int> ivec;
SRWLOCK g_lock;
SRWLOCK g_lock2;
CONDITION_VARIABLE g_ConditionVar;
int _tmain()
{
InitializeSRWLock(&g_lock); //初始化锁
HANDLE hThread1 = (HANDLE)_beginthreadex(NULL,0,(unsigned int(_stdcall *)(void*))ThreadProduce,NULL,0,0);
HANDLE hThread2 = (HANDLE)_beginthreadex(NULL, 0, (unsigned int(_stdcall *)(void*))ThreadUser1, NULL, 0, 0);
HANDLE hThread3 = (HANDLE)_beginthreadex(NULL, 0, (unsigned int(_stdcall *)(void*))ThreadUser2, NULL, 0, 0);
CloseHandle(hThread1);
CloseHandle(hThread2);
CloseHandle(hThread3);
_gettchar();
return 0;
}
DWORD WINAPI ThreadProduce(PVOID pvParam)
{
for (int i = 0; i < 10000; i++)
{
AcquireSRWLockExclusive(&g_lock); //获得SRW锁
ivec.push_back(i);
ReleaseSRWLockExclusive(&g_lock);//释放SRW锁
WakeConditionVariable(&g_ConditionVar);//因为每次执行完push_back后,容器里卖弄就会必定至少有一个元素(生产者)
//生产出东西了,这时候阻塞在Sleep*里面的线程就会被唤醒(读取者sleep线程)
Sleep(1);//停一下,让读取者先读
}
return 0;
}
DWORD WINAPI ThreadUser1(PVOID pvParam)
{
while (1)
{
AcquireSRWLockExclusive(&g_lock);
while (ivec.empty())
{
cout << "等待写入" << endl;
//如果容器是空的,也就是没有内容可以读,那么让线程进入睡眠状态,一直到调用WakeConditionAllVariable(&g_ConditionVar)
SleepConditionVariableSRW(&g_ConditionVar,&g_lock,INFINITE,0);
}
cout << "线程1:" << ivec.back() << endl;
ivec.pop_back();
ReleaseSRWLockExclusive(&g_lock);
}
return 0;
}
DWORD WINAPI ThreadUser2(LPVOID pvParam)
{
while (1)
{
AcquireSRWLockExclusive(&g_lock);
while (ivec.empty())
{
cout << "等待写入2"<<endl;
SleepConditionVariableSRW(&g_ConditionVar, &g_lock, INFINITE, 0);
}
cout << "线程2:" << ivec.back() << endl;
ivec.pop_back();
ReleaseSRWLockExclusive(&g_lock);
}
return 0;
}