- 论坛徽章:
- 0
|
编译:
gcc -lpthread test.c
运行:
./a.out 4 1 //4个线程写,暂停1us,不用fsync
./a.out 4 1 1 //用fsync
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <string.h>
- #include <errno.h>
- #include <pthread.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #define LEN 3*4000
- int fd;
- int need_sync = 0;
- int sync_done = 0;
- void run(void *arg)
- {
- char buf[LEN];
- int usecs = *((int *)arg);
- int n, i = 0;
- i = pthread_self()%255;
- memset(buf, i%31+'A', sizeof(buf));
- printf("%lu === %c\n", pthread_self(), i%31+'A');
- while(1)
- {
- sync_done = 0;
- lseek(fd, 0, 0);
- n = write(fd, buf, sizeof(buf));
- if(n != sizeof(buf)) printf("ERROR! ******* partial write ******\n");
- if(need_sync) fsync(fd);
- sync_done = 1;
- //fprintf(stdout, "%d:%08x:%d\n", i++, (int )pthread_self(), usecs);
- usleep(usecs);
- }
- }
- void see()
- {
- int nbad = 0;
- char buf[LEN];
- int r, n;
- r = 0;
- while(1) {
- while(sync_done == 0);
- lseek(fd, 0, 0);
- n = read(fd, buf, sizeof(buf));
- sync_done = 0;
- r++;
- if(r % 1024 == 0) printf("%d %d\n", r, n);
- if(buf[0] != buf[sizeof(buf)-8]) {
- printf("BAD DATA: %c --- %c\n", buf[0], buf[sizeof(buf)-8]);
- }
- //sleep(1);
- }
- }
- int main(int argc, char **argv)
- {
- int threads_num = 0;
- int sleep_usecs = 0;
- int i = 0;
- pthread_t thread_id = 0;
- if(argc < 3)
- {
- fprintf(stderr, "Usage:%s threads_num sleep_usec(s)\n", argv[0]);
- _exit(-1);
- }
- if(argv[3]) need_sync = 1;
- fd = open("./1111", O_CREAT | O_RDWR);
- printf("fd = %d\n", fd);
- threads_num = atoi(argv[1]);
- sleep_usecs = atoi(argv[2]);
- for(i = 0; i < threads_num; i++)
- {
- if(pthread_create(&thread_id, NULL, (void *)&run, (void *)&sleep_usecs) == 0)
- {
- fprintf(stdout, "created thread[%d][%08x] sleep_usecs:%d\n",
- i, (int )thread_id, sleep_usecs);
- }
- }
- pthread_create(&thread_id, NULL, (void *)&see, (void *)&sleep_usecs);
- while(1)
- {
- usleep(sleep_usecs);
- }
- return 0;
- }
复制代码 |
|