首先看一下源代码
#include <stdio.h>
#include <windows.h>
void test()
{
FILE *fp = fopen("d:\\aaa.txt", "a+");
fprintf(fp, "hello\n");
fclose(fp);
}
DWORD WINAPI ThreadFun(LPVOID pM)
{
test();
return 0;
}
int main()
{
printf("main thread\n");
int i = 0;
for(i = 0; i < 10; i++)
{
HANDLE handle = CreateThread(NULL, 0, ThreadFun, NULL, 0, NULL);
CloseHandle(handle);
}
getchar();
printf("end\n");
return 0;
}
执行时发现,不是每次都打印10个hello,有时打印9个,有时13个???
下面, 我们对用互斥对象对多线程下的文件操作进行保护(互斥锁), 简要的示意代码如下:
#include <stdio.h>
#include <windows.h>
HANDLE hMutex = NULL;
void test()
{
WaitForSingleObject(hMutex, INFINITE);
FILE *fp = fopen("d:\\aaa.txt", "a+");
fprintf(fp, "hello\n");
fclose(fp);
ReleaseMutex(hMutex);
}
DWORD WINAPI ThreadFun(LPVOID pM)
{
test();
return 0;
}
int main()
{
printf("main thread\n");
hMutex = CreateMutex(NULL, FALSE, NULL);
int i = 0;
for(i = 0; i < 10; i++)
{
HANDLE handle = CreateThread(NULL, 0, ThreadFun, NULL, 0, NULL);
CloseHandle(handle);
}
getchar();
printf("end\n");
return 0;
}
这下可以了,每次都打印10个hello!