Advertisement
Guest User

Untitled

a guest
Mar 25th, 2014
269
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // build it as gcc -std=c99 aio_race.c -o aio_race -lpthread -laio
  2.  
  3. #define _GNU_SOURCE
  4.  
  5. #include <pthread.h>
  6. #include <stdlib.h>
  7. #include <stdio.h>
  8. #include <sys/types.h>
  9. #include <sys/stat.h>
  10. #include <fcntl.h>
  11. #include <assert.h>
  12. #include <unistd.h>
  13. #include <string.h>
  14. #include <libaio.h>
  15. #include <stdbool.h>
  16.  
  17. #define PAGE_SIZE 4096
  18.  
  19. #define FILENAME "tempfile"
  20. #define FILEPATTERN '1'
  21. #define DESTROY_PATTERN '2'
  22.  
  23. #define THREADS_NUM 100
  24.  
  25. void remove_tempfile(void) {
  26.   assert(!unlink(FILENAME));
  27. }
  28.  
  29. void aio_worker(void *ptr) {
  30.   int fd = open(FILENAME, O_DIRECT | O_RDONLY);
  31.   char buffer[PAGE_SIZE] __attribute__((aligned(PAGE_SIZE)));
  32.  
  33.   while(true) {
  34.     io_context_t ctx;
  35.     struct iocb cb;
  36.     struct iocb *cbs[1];
  37.  
  38.     assert(!io_queue_init(1, &ctx));
  39.     io_prep_pread(&cb, fd, buffer, PAGE_SIZE, 0);
  40.     cbs[0] = &cb;
  41.  
  42.     memset(buffer, '0', PAGE_SIZE);
  43.     assert(io_submit(ctx, 1, &cbs[0]) == 1);
  44.     // wait random time (0-500ms) ?
  45.  
  46.     io_destroy(ctx);
  47.     memset(buffer, DESTROY_PATTERN, PAGE_SIZE);
  48.     // wait random for (0-500ms) ?
  49.  
  50.     // check it is still DESTROY_PATTERN
  51.     for (int i = 0; i < PAGE_SIZE; i++) {
  52.       if (buffer[i] != DESTROY_PATTERN) {
  53.         fprintf(stderr, "Buffer has unexpected character: %c\n", buffer[i]);
  54.         exit(EXIT_FAILURE);
  55.       }
  56.     }
  57.   }
  58.  
  59.   close(fd);
  60. }
  61.  
  62. int main(void) {
  63.   int fd = open(FILENAME, O_CREAT | O_TRUNC | O_APPEND | O_RDWR, S_IRUSR | S_IWUSR);
  64.   assert(fd != -1);
  65.   //atexit(remove_tempfile);
  66.  
  67.   char buffer[PAGE_SIZE];
  68.   memset(buffer, FILEPATTERN, PAGE_SIZE);
  69.   write(fd, buffer, PAGE_SIZE);
  70.   close(fd);
  71.  
  72.   pthread_t threads[THREADS_NUM];
  73.   for (int i = 0; i < THREADS_NUM; i++) {
  74.     assert(!pthread_create(&threads[i], NULL, (void *)&aio_worker, NULL));
  75.   }
  76.   for (int i = 0; i < THREADS_NUM; i++) {
  77.     assert(!pthread_join(threads[i], NULL));
  78.   }
  79.  
  80.   return EXIT_SUCCESS;
  81. }
Advertisement
RAW Paste Data Copied
Advertisement