同步訪問中的讀寫者問題(使用線程關(guān)鍵域)
#include <windows.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
struct CRITICAL_REGION

{
public:
CRITICAL_SECTION cs;
int gData;
};
DWORD WINAPI writer(LPVOID cr);
DWORD WINAPI reader(LPVOID cr);

int main(int argc,char* argv[])

{
DWORD targetThreadID;
HANDLE writerThread;
HANDLE readerThread;
CRITICAL_REGION cr;
cr.gData=0;
InitializeCriticalSection(&(cr.cs));
writerThread =CreateThread(NULL,0,writer,&cr,0,&targetThreadID);
CloseHandle(writerThread);
readerThread =CreateThread(NULL,0,reader,&cr,0,&targetThreadID);
CloseHandle(readerThread);
Sleep(10000);
printf("end");
return 0;
}
DWORD WINAPI writer(LPVOID cr)

{
Sleep(1000);
DWORD result = 0;
int n = 1;
ExitProcess(0);
while(n<=10)
{
EnterCriticalSection(&((CRITICAL_REGION*)cr)->cs);
if(((CRITICAL_REGION*)cr)->gData==0)
{
((CRITICAL_REGION*)cr)->gData = n;
printf("gData is %d\n",((CRITICAL_REGION*)cr)->gData);
n++;
}
LeaveCriticalSection(&(((CRITICAL_REGION*)cr)->cs));
Sleep(100);
}
return result;
};
DWORD WINAPI reader(LPVOID cr)

{
DWORD result =0;
char u[6];
int n = 1;
while(n<=10)
{
EnterCriticalSection(&((CRITICAL_REGION*)cr)->cs);
if(((CRITICAL_REGION*)cr)->gData!=0)
{
((CRITICAL_REGION*)cr)->gData = 0;
n++;
printf("gData is taken away\n");
}
LeaveCriticalSection(&(((CRITICAL_REGION*)cr)->cs));
Sleep(50);
}
DeleteCriticalSection( &(((CRITICAL_REGION*)cr)->cs));
gets(u);
return result;
};posted on 2009-08-12 18:24 把握命運(yùn) 閱讀(245) 評(píng)論(0) 編輯 收藏 引用
