依睛(IT blog) 我回来了,PHP<-->C/C++ LINUX

笨鸟

统计

积分与排名

友情连接

最新评论

两个线程同时向一个文件写数据

#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;
}

posted on 2008-12-29 12:25 向左向右走 阅读(538) 评论(0)  编辑 收藏 引用 所属分类: C/C++学习资料库

只有注册用户登录后才能发表评论。