多个线程同时执行对某个全局变量进行访问时,可能会引发一些错误,所以就需要引入线程互斥事件
线程互斥事件会对线程做一个排序,使得在访问同一个全局变量时不会出错
HANDLE CreateEventA(
[in, optional] LPSECURITY_ATTRIBUTES lpEventAttributes,//安全属性
[in] BOOL bManualReset,//T为手动重置,F为自动重置
[in] BOOL bInitialState,//F为无信号
[in, optional] LPCSTR lpName//事件对象的名称
);
使用CreateEvent创建互斥事件,在线程中使用WaitForSingleObject来等待启动线程
unsigned WINAPI QueryOthers(void* arg)
{
int i, cnt = 0;
WaitForSingleObject(hEvent, INFINITE);
for (i = 0; str[i] != 0; i++)
{
if (str[i] != 'A')
{
str[i]='c';
}
}
printf("B=%s\n", str);
return 0;
}
而在另一线程中则使用SetEvent来启动等待的线程
unsigned WINAPI QueryAs(void* arg)
{
int i, cnt = 0;
for (i = 0; str[i] != 0; i++)
{
if (str[i] == 'A')
{
str[i]='a';
}
}
printf("A=%s\n", str);
SetEvent(hEvent);
return 0;
}
这样就会有序的对同一个全局变量访问,而不至于出错
整体代码:
#include<stdio.h>
#include<process.h>
#include<windows.h>
char str[100];
HANDLE hEvent;
unsigned WINAPI QueryAs(void* arg)
{
int i, cnt = 0;
for (i = 0; str[i] != 0; i++)
{
if (str[i] == 'A')
{
str[i]='a';
}
}
printf("A=%s\n", str);
SetEvent(hEvent);
return 0;
}
unsigned WINAPI QueryOthers(void* arg)
{
int i, cnt = 0;
WaitForSingleObject(hEvent, INFINITE);
for (i = 0; str[i] != 0; i++)
{
if (str[i] != 'A')
{
str[i]='c';
}
}
printf("B=%s\n", str);
return 0;
}
int main()
{
HANDLE hThread1, hThread2;
fputs("请输入\n", stdout);
fgets(str, 100, stdin);
hEvent = CreateEvent(NULL, TRUE, false, NULL);
hThread1 = (HANDLE)_beginthreadex(NULL, 0, QueryAs, NULL, 0, NULL);
hThread2 = (HANDLE)_beginthreadex(NULL, 0, QueryOthers, NULL, 0, NULL);
WaitForSingleObject(hThread1,INFINITE);
WaitForSingleObject(hThread2, INFINITE);
ResetEvent(hEvent);
CloseHandle(hEvent);
return 0;
}
运行结果如下: