
#include <stdio.h>
#include <Windows.h>
#define MAX_THREAD 10
typedef struct
{
char thread_name[3];
unsigned int require_moment;
unsigned int persist_time;
}TEST_INFO;
TEST_INFO test_data[MAX_THREAD]=
{
{"r1",0,1},
{"r2",1,1},
{"w1",3,3},
{"r3",4,2},
{"w2",5,6},
{"w3",6,10},
{"r4",7,8},
{"r5",9,2},
{"w4",10,18},
{"w5",12,2}
};
CRITICAL_SECTION CS_DATA;
HANDLE h_mutex_read_count=CreateMutex(NULL,FALSE,"mutex_read_count");
HANDLE h_mutex_write_count=CreateMutex(NULL,FALSE,"mutex_write_count");
HANDLE h_mutex_reader_wait=CreateMutex(NULL,FALSE,"mutex_reader_wait");
HANDLE h_mutex_first_reader_wait=CreateMutex(NULL,FALSE,"mutex_first_reader_wait");
int read_count=0;
int write_count=0;
void WF_reader_thread(void *data)
{
char thread_name[3];
strcpy(thread_name,((TEST_INFO*)data)->thread_name);
Sleep(((TEST_INFO*)data)->require_moment*1000);
WaitForSingleObject(h_mutex_reader_wait,-1);
WaitForSingleObject(h_mutex_first_reader_wait,-1);
WaitForSingleObject(h_mutex_read_count,-1);
read_count++;
if(read_count==1)
EnterCriticalSection(&CS_DATA);
ReleaseMutex(h_mutex_read_count);
ReleaseMutex(h_mutex_first_reader_wait);
ReleaseMutex(h_mutex_reader_wait);
printf("%s",thread_name);
Sleep(((TEST_INFO*)data)->persist_time*1000);
WaitForSingleObject(h_mutex_read_count,-1);
read_count--;
if(read_count==0)
LeaveCriticalSection(&CS_DATA);
ReleaseMutex(h_mutex_read_count);
}
void WF_writer_thread(void *data)
{
Sleep(((TEST_INFO*)data)->require_moment*1000);
WaitForSingleObject(h_mutex_write_count,-1);
if(write_count==0)
WaitForSingleObject(h_mutex_first_reader_wait,-1);
write_count++;
ReleaseMutex(h_mutex_write_count);
EnterCriticalSection(&CS_DATA);
printf("%s",((TEST_INFO*)data)->thread_name);
Sleep(((TEST_INFO*)data)->persist_time*1000);
LeaveCriticalSection(&CS_DATA);
WaitForSingleObject(h_mutex_write_count,-1);
write_count--;
if(write_count==0)
ReleaseMutex(h_mutex_first_reader_wait);
ReleaseMutex(h_mutex_write_count);
}
void write_first()
{
int i=0;
HANDLE h_thread[MAX_THREAD];
printf("写优先申请次序:");
for(i=0;i<MAX_THREAD;i++)
{
printf("%s",test_data[i].thread_name);
}
printf("\n");
printf("写优先操作次序:");
InitializeCriticalSection(&CS_DATA);
for(i=0;i<MAX_THREAD;i++)
{
if(test_data[i].thread_name[0]=='r')
h_thread[i]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(WF_reader_thread),&test_data[i],0,NULL);
else
h_thread[i]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(WF_writer_thread),&test_data[i],0,NULL);
}
WaitForMultipleObjects(MAX_THREAD,h_thread,TRUE,-1);
printf("\n");
}
void main()
{
write_first();
while(1)
{
WF_writer_thread(test_data);
WF_reader_thread(test_data);
}
}