死锁

第一个写死锁的程序,不多说了,说多了都是泪。。。权当留念。。。
#include
#include
#include
#include
#include
#include
#include

volatile LONG cntR, cntW, waitR;
HANDLE mutexR, mutexW;
HANDLE readEvent, writeEvent;
int val;

DWORD WINAPI ReaderThread(PVOID pvParam);
DWORD WINAPI WriterThread(PVOID pvParam);
void initRand();

int main(int argc, char **argv){
HANDLE flag;
DWORD threadId;
val = 0;

mutexR = CreateMutex(NULL, 0, NULL);
mutexW = CreateMutex(NULL, 0, NULL);
writeEvent = CreateEvent(NULL, 0, true, NULL);
readEvent = CreateEvent(NULL, 1, true, NULL);
while (true){
srand(time(NULL));
int r = rand() % 4;
if (r == 0){
flag = CreateThread(NULL, 0, WriterThread, NULL, 0, &threadId);
if (flag)
printf("Writer thread %d created...\n", threadId);
else
printf("Error %d while creating Writer thread\n", GetLastError());
CloseHandle(flag);
}
else{
flag = CreateThread(NULL, 0, ReaderThread, NULL, 0, &threadId);
if (flag)
printf("Reader thread %d created...\n", threadId);
else
printf("Error %d while creating Reader thread\n", GetLastError());
CloseHandle(flag);
}
Sleep(1000);
}
}

DWORD WINAPI ReaderThread(PVOID pvParam){
InterlockedAdd(&waitR, 1);
WaitForSingleObject(readEvent, INFINITE);
InterlockedAdd(&waitR, -1);

ResetEvent(writeEvent);
WaitForSingleObject(mutexR, INFINITE);
cntR++;
int threadId = GetCurrentThreadId();
printf("This is reader %d, val = %d\n", threadId, val);
ReleaseMutex(mutexR);

Sleep(1500);

WaitForSingleObject(mutexR, INFINITE);
cntR--;
printf("Reader %d leaving, still %d readers reading, %d readers waiting\n\n", threadId, cntR, waitR);
if (cntR == 0)
SetEvent(writeEvent);
ReleaseMutex(mutexR);
return 0;
}

DWORD WINAPI WriterThread(PVOID pvParam){
WaitForSingleObject(mutexW, INFINITE);
cntW++;
ReleaseMutex(mutexW);
//不能用InterlockedIncrement(&cntW);必须用同一种内核同步对象来控制

ResetEvent(readEvent);
WaitForSingleObject(writeEvent, INFINITE);
int threadId = GetCurrentThreadId();
initRand();
val = rand();
printf("This is %d writing, val equals %d\n", threadId, val);
Sleep(3500);

WaitForSingleObject(mutexW, INFINITE);
cntW--;
if (cntW == 0)
SetEvent(readEvent);
printf("Writer %d leaving, %d writers waiting\n\n", threadId, cntW);
ReleaseMutex(mutexW);
return 0;
}

void initRand(){
// 如果支持高性能精度计数器,则使用其初始化随机种子(微秒级)
LARGE_INTEGER nFrequency;
if (::QueryPerformanceFrequenc y(&nFrequency))
{
LARGE_INTEGER nStartCounter;
QueryPerformanceCounter(&nStartCounter);
srand((unsigned)nStartCounter.LowPart);
}
else // 否则使用当前系统时间初始化随机种子(毫秒级)
{
timeb stb;
ftime(&stb);
srand((unsigned)stb.millitm);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值