读书人

急多线程对文件操作高高手,该如何解

发布时间: 2012-02-28 13:06:36 作者: rapoo

急!!!多线程对文件操作,高高手
本我采用unicode格式,写入日志文件
多线程里经常调用这个函数
日志文件中加入了临界区,同步
一秒钟可能向文件操作N次,不同的线程.频繁open()-> write()-> close()
执行2分钟后,DEBUG出现异常
错误提示为File *fp.(stream !=NULL),fwrite.c文件
还有这种提示fputwc函数 (str!=NULL) fputws.c文件
-------------------------------------------------------
有没有高手解决呀!什么原因会这样呀,都加了同步控制

[解决办法]
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

CRITICAL_SECTION cs;
FILE* f;

void thread_func( void* ptr )
{
DWORD id = GetCurrentThreadId();
int i;
char tbuf[16];

if( f == NULL )
{
printf( "file is null\n " );
return;
}

for( i = 0; i < 10000; i ++ )
{
EnterCriticalSection( &cs );
printf( "thread <%d> : %s <%d> \n ", id, _strtime( tbuf ), i );
fprintf( f, "thread <%d> : %s <%d> \n ", id, _strtime( tbuf ), i );
fflush( f );
LeaveCriticalSection( &cs );
}

return ;
}

int main(int argc, char *argv[])
{
int i;
int thandles[10];
if( ( f = fopen( "log.txt ", "a+ " ) ) == NULL )
{
printf( "fopen failed:%d\n ", GetLastError() );
return;
}

InitializeCriticalSection( &cs );

for( i = 0; i < sizeof( thandles ) / sizeof( thandles[0] ); i ++ )
thandles[i] = _beginthread( thread_func, 0, 0 );

WaitForMultipleObjects( sizeof( thandles ) / sizeof( thandles[0] ),
thandles,
1,
60 * 1000 );

fclose( f );

DeleteCriticalSection( &cs );

system( "PAUSE ");
return 0;

}

读书人网 >C语言

热点推荐