多线程练习----读者写者问题

#include <windows.h>
#include <iostream>
#include <process.h>
#include <cstdlib>
#include <ctime>

using namespace std;
DWORD WINAPI Reader(LPVOID lpParameter);
DWORD WINAPI Writer(LPVOID lpParameter);


//全局变量
CRITICAL_SECTION ReaderMutex, WriteMutex;//这个变量用来保证输出时不会竞争
CRITICAL_SECTION WritePrior;
int ReaderCount = 0;

int main(int argc,char *argv[])
{
	HANDLE hthread[5];
	HANDLE hWriter;
	int i;
	int arg[5];
	int count = 5;
	unsigned long retval;


	InitializeCriticalSection(&WriteMutex);
	InitializeCriticalSection(&ReaderMutex);
	InitializeCriticalSection(&WritePrior);

	for(i = 0; i<5;i++)
	{
		arg[i] = i;
		hthread[i] = CreateThread(NULL, 0, Reader, (void*)(arg+i), 0, NULL);
		if( hthread[i] == INVALID_HANDLE_VALUE)//如果线程创建失败返回-1
		{
			cerr << "error while create thread " << i <<endl;
			cerr << "error code : "<< GetLastError() <<endl;
		}
	}


	hWriter = CreateThread(NULL, 0, Writer, NULL, 0, NULL);
	//等待所有线程结束
	retval = WaitForMultipleObjects(5,hthread,true,INFINITE);//等待多个线程
	if(retval == WAIT_FAILED)
	{
		cerr<< "wait error,error code: "<<GetLastError()<<endl;
	}
	for(i = 0; i<5;i++)
	{
		if(CloseHandle(hthread[i]) == false)//关闭句柄
		{
			cerr << "error while close thread " <<i<<endl;
			cerr << "error code: "<<GetLastError()<<endl;
		}
	}

	DeleteCriticalSection( &WriteMutex);
	DeleteCriticalSection( &ReaderMutex);
	DeleteCriticalSection( &WritePrior);
	return 0;
}


DWORD WINAPI Reader(LPVOID lpParameter)
{
	int n = ((int *)lpParameter)[0];
	while(true)
	{
		//EnterCriticalSection( &WritePrior);
		EnterCriticalSection( &ReaderMutex);
		if ( ReaderCount == 0 )EnterCriticalSection(&WriteMutex);
		ReaderCount++;
		LeaveCriticalSection( &ReaderMutex);
		cout << "Reader " << n << "is reading " << endl;
		Sleep(15);

		EnterCriticalSection( &ReaderMutex);
		ReaderCount--;
		if ( ReaderCount == 0 )LeaveCriticalSection(&WriteMutex);
		LeaveCriticalSection( &ReaderMutex);
		//LeaveCriticalSection( &WritePrior);
		Sleep(1);
	}

	return n;
}


DWORD WINAPI Writer(LPVOID lpParameter)
{

	while(true)
	{
		//EnterCriticalSection( &WritePrior);
		EnterCriticalSection( &WriteMutex);
		cout << "Process write. The number of reader:" << ReaderCount<< endl;
		Sleep(15);
		LeaveCriticalSection( &WriteMutex);
		//LeaveCriticalSection( &WritePrior);
		//Sleep(10);
	}
	return 0;
}

你可能感兴趣的:(thread,多线程,null,include,winapi)