首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

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

2012-02-28 
急!!!多线程对文件操作,高高手本我采用unicode格式,写入日志文件多线程里经常调用这个函数日志文件中加入

急!!!多线程对文件操作,高高手
本我采用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;

}

热点排行