windows下一般有四种线程同步的方法:
(1)事件
(2)信号量
(3)互斥量
(4)临界区
下面将展示各自的用法
(1)事件
#include <stdio.h>
#include <windows.h>
int g = 0;
HANDLE events;
DWORD WINAPI ThreadFun1(PVOID pParam)
{
while (g < 100)
{
WaitForSingleObject(events, INFINITE);
g++;
printf("Thread1:%d\n", g);
SetEvent(events);
}
return 0;
}
DWORD WINAPI ThreadFun2(PVOID pParam)
{
while (g < 100)
{
WaitForSingleObject(events, INFINITE);
g++;
printf("Thread2:%d\n", g);
SetEvent(events);
}
return 0;
}
int main()
{
HANDLE hand1 = CreateThread(NULL, 0, ThreadFun1, NULL, 0, NULL);
HANDLE hand2 = CreateThread(NULL, 0, ThreadFun2, NULL, 0, NULL);
events = CreateEvent(NULL, FALSE, FALSE, NULL);
SetEvent(events);
char ch = getchar();
return 0;
}
输出结果:
(2)信号量
#include <stdio.h>
#include <windows.h>
int g = 0;
HANDLE sema;
DWORD WINAPI ThreadFun1(PVOID pParam)
{
while (g < 100)
{
WaitForSingleObject(sema, INFINITE);
g++;
printf("Thread1:%d\n", g);
ReleaseSemaphore(sema, 1, NULL);
}
return 0;
}
DWORD WINAPI ThreadFun2(PVOID pParam)
{
while (g < 100)
{
WaitForSingleObject(sema, INFINITE);
g++;
printf("Thread2:%d\n", g);
ReleaseSemaphore(sema, 1, NULL);
}
return 0;
}
int main()
{
HANDLE hand1 = CreateThread(NULL, 0, ThreadFun1, NULL, 0, NULL);
HANDLE hand2 = CreateThread(NULL, 0, ThreadFun2, NULL, 0, NULL);
sema = CreateSemaphore(NULL, 1, 1, NULL);
char ch = getchar();
return 0;
}
输出结果:
(3)互斥量
#include <stdio.h>
#include <windows.h>
int g = 0;
HANDLE Mutex;
DWORD WINAPI ThreadFun1(PVOID pParam)
{
while (g < 100)
{
WaitForSingleObject(Mutex, INFINITE);
g++;
printf("Thread1:%d\n", g);
ReleaseMutex(Mutex);
}
return 0;
}
DWORD WINAPI ThreadFun2(PVOID pParam)
{
while (g < 100)
{
WaitForSingleObject(Mutex, INFINITE);
g++;
printf("Thread2:%d\n", g);
ReleaseMutex(Mutex);
}
return 0;
}
int main()
{
HANDLE hand1 = CreateThread(NULL, 0, ThreadFun1, NULL, 0, NULL);
HANDLE hand2 = CreateThread(NULL, 0, ThreadFun2, NULL, 0, NULL);
Mutex = CreateMutex(NULL, FALSE, NULL);
char ch = getchar();
return 0;
}
输出结果:
(4)临界区
#include <stdio.h>
#include <windows.h>
int g = 0;
CRITICAL_SECTION g_cs;
DWORD WINAPI ThreadFun1(PVOID pParam)
{
while (g < 100)
{
EnterCriticalSection(&g_cs);
g++;
printf("Thread1:%d\n", g);
LeaveCriticalSection(&g_cs);
}
return 0;
}
DWORD WINAPI ThreadFun2(PVOID pParam)
{
while (g < 100)
{
EnterCriticalSection(&g_cs);
g++;
printf("Thread2:%d\n", g);
LeaveCriticalSection(&g_cs);
}
return 0;
}
int main()
{
HANDLE hand1 = CreateThread(NULL, 0, ThreadFun1, NULL, 0, NULL);
HANDLE hand2 = CreateThread(NULL, 0, ThreadFun2, NULL, 0, NULL);
InitializeCriticalSection(&g_cs);
char ch = getchar();
return 0;
}
输出结果:
总结:四种方法中只有临界区未达到预期的效果。