您的位置:首页 > 其它

【讨论】文件操作的原子性

2009-09-14 18:19 155 查看
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>

const char *fileName = "/dev/sram-mmap";  //"test"

#define SleepMs( ms ) ( usleep( (ms)*1000 ) )
#define TRUE 1
#define FALSE 0
#define BUFLEN (65536)

int  createThread( pthread_t  *thread, pthread_attr_t * attr, void *(*start_routine)(void *), void * arg )
{
if ( pthread_create( thread, attr, start_routine, arg ) )  //成功则返回0
{
return FALSE;
}

return TRUE;
}

void doing( int fd, const void *buf, int len )
{
write( fd, buf, len );
}

void *tFun0( void * )
{
char buf[BUFLEN];
memset( buf, 0x0, sizeof(buf) );
while(1 )
{
int fd = open( fileName, O_RDWR );
doing( fd, buf, sizeof(buf) );
close(fd);
}
}

void *tFun1( void * )
{
char buf[BUFLEN];
memset( buf, 0x1, sizeof(buf) );
while(1 )
{
int fd = open( fileName, O_RDWR );
doing( fd, buf, sizeof(buf) );
close(fd);
}
}

void *tFun2( void * )
{
char buf[BUFLEN];
memset( buf, 0x2, sizeof(buf) );
while(1 )
{
int fd = open( fileName, O_RDWR );
doing( fd, buf, sizeof(buf) );
close(fd);
}
}

void *tFun3( void * )
{
char buf[BUFLEN];
memset( buf, 0x3, sizeof(buf) );
while(1 )
{
int fd = open( fileName, O_RDWR );
doing( fd, buf, sizeof(buf) );
close(fd);
}
}

int main()
{
pthread_t touch_thread[10];
createThread( &touch_thread[0], NULL, tFun0, NULL );
createThread( &touch_thread[1], NULL, tFun1, NULL );
createThread( &touch_thread[2], NULL, tFun2, NULL );
createThread( &touch_thread[3], NULL, tFun3, NULL );

SleepMs(10);
char oldVal = 0;
char buf[BUFLEN];
memset( buf, 0x0, sizeof(buf) );
while(1 )
{
int fd = open( fileName, O_RDWR );
int len = read( fd, buf, sizeof(buf) );
close(fd);
char val = buf[0];
if ( oldVal != val )
{
printf( "curVal = %x/n", val );
oldVal = val;
}
for ( int i = 1; i < len; ++i )
{
if ( buf[i] != val )
{
printf( "error:val = %x,buf[%d] = %x/n", val, i, buf[i] );
}
}
}
}


//经测试:
//(测试平台X86/Linux)
//#define BUFLEN (65536) (8192) (4097) 时,存在不一致的情况.(4096)则不存在不一致。
//说明一个块大小(4096B)的读写是原子的,不会被其他线程打断.

//(测试平台ARM/Linux,测试SRAM设备文件)
//#define BUFLEN (65536)时,没有不一致的情况。

//以上测试结果与<<【071108】文件操作的原子性>>的结果一致。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: