线程同步(临界区的使用)
Posted 刘收获
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程同步(临界区的使用)相关的知识,希望对你有一定的参考价值。
1.SingalObject
#include <windows.h>
#include <iostream>
using namespace std;
CRITICAL_SECTION cs;
int m = 0;
int n = 0;
DWORD WINAPI ThreadProc(LPVOID Param);
int main()
{
InitializeCriticalSection(&cs);
int a = 10;
HANDLE ThreadHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadProc,NULL, 0, NULL);
EnterCriticalSection(&cs);
for (int i = 0;i<1000;i++)
{
m++;
n++;
printf("Main Thread\r\n");
}
LeaveCriticalSection(&cs);
WaitForSingleObject(ThreadHandle, INFINITE);
1.SingalObeject
DeleteCriticalSection(&cs);
printf("%d %d\r\n", m, n);
}
DWORD WINAPI ThreadProc(LPVOID Param)
{
EnterCriticalSection(&cs);
for (int i = 0; i < 1000; i++)
{
printf("Sub Thread\r\n");
m++;
n++;
}
LeaveCriticalSection(&cs);
return 0;
}
2.MultipleObject
#include <windows.h>
#include <iostream>
using namespace std;
CRITICAL_SECTION cs;
int m = 0;
int n = 0;
DWORD WINAPI ThreadProc(LPVOID Param);
int main()
{
HANDLE ThreadHandle[5] = { 0 };
InitializeCriticalSection(&cs);
for (int i = 0; i < 5; i++)
{
ThreadHandle[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadProc, NULL, 0, NULL);
}
WaitForMultipleObjects(5, ThreadHandle, TRUE, INFINITE);
DeleteCriticalSection(&cs);
printf("%d %d\r\n", m, n);
}
DWORD WINAPI ThreadProc(LPVOID Param)
{
CRITICAL_SECTION cs;
EnterCriticalSection(&::cs); //注意(&::cs)
for (int i=0;i<10000;i++)
{
m++;
n++;
}
LeaveCriticalSection(&::cs); //注意(&::cs)
return 0;
}
以上是关于线程同步(临界区的使用)的主要内容,如果未能解决你的问题,请参考以下文章