死锁

来源:互联网 发布:热血江湖怪物数据 2017 编辑:程序博客网 时间:2024/04/30 06:12
第一个写死锁的程序,不多说了,说多了都是泪。。。权当留念。。。
#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, %dreaders 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 (::QueryPerformanceFrequency(&nFrequency))
{
LARGE_INTEGER nStartCounter;
QueryPerformanceCounter(&nStartCounter);
srand((unsigned)nStartCounter.LowPart);
}
else // 否则使用当前系统时间初始化随机种子(毫秒级)
{
timeb stb;
ftime(&stb);
srand((unsigned)stb.millitm);
}
}
0 0
原创粉丝点击