线程间使用SRW轻量级锁共享变量

SRWLOCK  g_lock = {};        //轻量级锁
CONDITION_VARIABLE  g_val={};//轻量级锁的同步条件
INT  iGlobal = 0;            //读写的全局变量
DWORD  WINAPI  WriteThread(LPVOID lpParameter)
{//写线程
	while (1)
	{  
		Sleep(20);
		__try
		{
			AcquireSRWLockExclusive(&g_lock);//申请独占锁
			iGlobal++;
		}
		__finally
		{
			ReleaseSRWLockExclusive(&g_lock);//释放独占锁
			WakeAllConditionVariable(&g_val);//唤醒条件变量
		}
	}
	return 0;
}

DWORD WINAPI  ReadThread(LPVOID lpParameter)
{//读线程
	while (true)
	{   
		Sleep(30);
		__try
		{
			AcquireSRWLockShared(&g_lock);//申请共享锁
			BOOL rt = SleepConditionVariableSRW(&g_val, &g_lock, 20, 
			                     CONDITION_VARIABLE_LOCKMODE_SHARED);//等待条件变量
			if (rt)
			{
				char str[20] = {};
				itoa(iGlobal, str, 10);
				TRACE(str);
			}
 			else
 			{
				char str[20] = {};
				itoa(iGlobal, str, 10);
				TRACE(str);
			}
		}
		__finally
		{
			ReleaseSRWLockShared(&g_lock);//释放锁
		}
	}
	return 0;
}

void CtestThreadDlg::OnBnClickedButton15()
{
	InitializeSRWLock(&g_lock);
	InitializeConditionVariable(&g_val);
	
	DWORD  ThreadID =0;
	HANDLE  hWrite = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)WriteThread, 
	                     NULL, CREATE_SUSPENDED, &ThreadID);
	HANDLE  hRead  = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ReadThread, 
	                     NULL, CREATE_SUSPENDED, &ThreadID);

	ResumeThread(hWrite);
	ResumeThread(hRead);
}

当前文章:线程间使用SRW轻量级锁共享变量
文章起源:http://scyanting.com/article/johedp.html