今天晚上总算有点收获,写服务器,要用到(多读/单写)互斥,也就是MutiRead/SingleWrite互斥的实现,采用用非信号量来实现,用户模式,非内核模式,实现高效的线程调度
源代码如下:
// ThreadTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <process.h>
#include <windows.h>
#include <stdio.h>
//关键区锁
class MemLock {
CRITICAL_SECTION _crisection;
public:
MemLock(){
InitializeCriticalSection( &_crisection );
}
~MemLock(){
DeleteCriticalSection( &_crisection );
}
void lock() {
EnterCriticalSection( &_crisection );
}
void unlock() {
LeaveCriticalSection( &_crisection );
}
};
//共用资源
class ShareSource
{
MemLock mlock;
volatile LONG g_bResourceUse;
volatile LONG g_bResourceUse1;
int j;
public:
ShareSource()
{
g_bResourceUse = 0;
g_bResourceUse1 = 0;
}
void read(char *user)
{
while(InterlockedIncrement(&g_bResourceUse)>0)
{
if(g_bResourceUse1==0)
{
printf("用户%s 开始读 ", user);
Sleep(100);
printf("用户%s 正在读..", user);
Sleep(100);
printf("用户%s 读完了 \r\n", user);
Sleep(100);
}
InterlockedDecrement(&g_bResourceUse);
Sleep(10);
//printf("%d \r\n", j);
}
}
void write(char *user)
{
mlock.lock();
while(InterlockedIncrement(&g_bResourceUse1)>0 )
{
if(g_bResourceUse==0)
{
printf("[用户%s 开始写..", user);
Sleep(100);
printf("用户%s 正在写..", user);
Sleep(100);
printf("用户%s 写完了]..\r\n", user);
Sleep(100);
}
InterlockedDecrement(&g_bResourceUse1);
Sleep(10);
}
mlock.unlock();
}
};
class ThreadTest
{
public:
char user[20];
ShareSource * share;
HANDLE hThread;
ThreadTest(char *_user, ShareSource * source)
{
strcpy(user, _user); //用户名
hThread = 0;
share = source;
}
//工作线程的方法
static unsigned __stdcall WorkThreadCallBackMothodRead(LPVOID param) {
ThreadTest *th = (ThreadTest *) param;
while(1)
th->share->read(th->user);
return 0;
}
//工作线程的方法
static unsigned __stdcall WorkThreadCallBackMothodWrite(LPVOID param) {
ThreadTest *th = (ThreadTest *) param;
while(1)
th->share->write(th->user);
return 0;
}
//开始读线程
void BeginReadThread()
{
hThread = (HANDLE) _beginthreadex(0, 0, ThreadTest::WorkThreadCallBackMothodRead, (LPVOID)this , 0, 0);
}
//开始写线程
void BeginWriteThread()
{
hThread = (HANDLE) _beginthreadex(0, 0, ThreadTest::WorkThreadCallBackMothodWrite, (LPVOID)this , 0, 0);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
ShareSource source;
ThreadTest T1("T1", &source);
ThreadTest T2("T2", &source);
ThreadTest T3("T3", &source);
//前面两个读
T1.BeginReadThread();
T2.BeginReadThread();
//最后一个线程写
T3.BeginWriteThread();
getchar();
return 0;
}