【讨论】文件操作的原子性
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】文件操作的原子性>>的结果一致。
相关文章推荐
- UNIX高级环境编程(2)FIle I/O - 原子操作、共享文件描述符和I/O控制函数
- php原子操作,文件锁flock,数据库事务
- 利用temp文件实现原子操作
- nginx进程间的通信机制源码分析(二)-------原子操作、自旋锁、文件锁
- 关于文件I/o的原子操作
- i++ 原子操作的讨论 转自http://gcoder.blogbus.com/logs/75275569.html
- UNIX高级环境编程(2)FIle I/O - 原子操作、共享文件描述符和I/O控制函数
- 利用temp文件实现原子操作
- 一个打开并创建文件操作引发的讨论
- 不使用锁的情况下对文件的原子操作
- 第六篇:一个打开并创建文件操作引发的讨论
- 第3章 文件I/O(3)_内核数据结构、原子操作
- 3.11 文件I/O_原子操作
- 多线程的文件读写操作讨论
- 误操作删除数据文件恢复案例讨论
- 由unix文件I/O引出的原子操作
- 关于文件I/o的原子操作
- 四、文件IO——内核数据结构和原子操作
- 文件IO中的原子操作
- 【讨论】简析文件操作