#include <windows.h>
#include <string.h>
#include <stdio.h>
typedef struct FILE_1{
FILE * fp;
int id;
}FILE_1;
HANDLE hmutex;
size_t safewrite(FILE_1 * safefp, size_t offset, void * pdata, int size)
{
int len;
// /* lock file */
if (WAIT_OBJECT_0 != WaitForSingleObject(hmutex, INFINITE))
return ERROR;
/* seek the file pointer to offset */
fseek(safefp->fp, offset, SEEK_SET);
/* write */
len = fwrite(pdata, 1, size, safefp->fp);
/* unlock */
ReleaseMutex(hmutex) ;
return len;
}
DWORD WINAPI ThreadFunc(FILE_1 * file)
{
int offset;
char buf[1024];
int i;
offset = file->id * (10*1024);
memset(buf, 'a'+file->id, sizeof(buf));
for (i=0; i<10; i++)
{
printf("%c", 'a'+file->id);
safewrite(file, offset, buf, sizeof(buf));
offset += sizeof(buf);
}
return 0;
}
int main(int argc,char* argv[])
{
HANDLE Thread[2];
DWORD dwThreadId;
int i=0;
FILE_1 file2[2];
file2[0].fp = fopen("t.txt", "wb");
file2[1].fp = file2[0].fp;
hmutex = CreateMutex(NULL, FALSE, NULL);
for (i=0; i<2; i++)
{
file2[i].id = i;
Thread[i]=CreateThread(NULL,0,ThreadFunc,&file2[i],0,&dwThreadId);
}
WaitForSingleObject(Thread[0],INFINITE);
WaitForSingleObject(Thread[1],INFINITE);
CloseHandle(Thread[0]);
CloseHandle(Thread[1]);
fclose(file2[0].fp);
fclose(file2[1].fp);
return 0;
}