线程同步的几种方法

来源:互联网 发布:阿里云上传域名证书 编辑:程序博客网 时间:2024/06/07 22:24

1:临界区(关键段)

2:互斥量

3:事件

4:信号量


int g_count = 0;

//CRITICAL_SECTION g_cs;
//HANDLE g_hMutex = NULL;
//HANDLE g_hEvent = NULL;
HANDLE   g_hSemaphore = NULL;


DWORD WINAPI threadFun1(LPVOID lpParam)
{
while (true)
{
//EnterCriticalSection(&g_cs);
//WaitForSingleObject(g_hMutex, INFINITE);
//WaitForSingleObject(g_hEvent, INFINITE);
WaitForSingleObject(g_hSemaphore, INFINITE);
cout << "th1:" << g_count++ << endl;
//LeaveCriticalSection(&g_cs);
//ReleaseMutex(g_hMutex);
//SetEvent(g_hEvent);
ReleaseSemaphore(g_hSemaphore,1,NULL);
Sleep(50);
}
return 0;
}


DWORD WINAPI threadFun2(LPVOID lpParam)
{
while (true)
{
//EnterCriticalSection(&g_cs);
//WaitForSingleObject(g_hMutex, INFINITE);
//WaitForSingleObject(g_hEvent, INFINITE);
WaitForSingleObject(g_hSemaphore, INFINITE);
cout << "th2:" << g_count++ << endl;
//LeaveCriticalSection(&g_cs);
//ReleaseMutex(g_hMutex);
//SetEvent(g_hEvent);
ReleaseSemaphore(g_hSemaphore, 1, NULL);
Sleep(50);
}
return 0;
}


int main()
{
//InitializeCriticalSection(&g_cs);
//g_hMutex = CreateMutex(NULL, FALSE, L"g_hMutex");
//g_hEvent = CreateEvent(NULL, FALSE, TRUE, L"g_hEvent");
g_hSemaphore = CreateSemaphore(NULL, 1, 1, L"g_hSemaphore");


CreateThread(NULL, 0, threadFun1, NULL, 0, NULL);
CreateThread(NULL, 0, threadFun2, NULL, 0, NULL);


while (true);
system("pause");
return 0;
}
原创粉丝点击