summaryrefslogtreecommitdiff
path: root/io_cache_test/io_cache_test.cpp
blob: 5bb8dd0f1db4d3df735ec85f380308aae2c09614 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "my_sys.h"
#include "pthread.h"
#include "time.h"
#include "ring_buffer.hpp"
#include <fstream>

RingBuffer *cache;
uchar *buff_from;
uchar *buff_to;
pthread_barrier_t barrier;

void *read_to_cache(void *) {
  pthread_barrier_wait(&barrier);
  for (int i= 0; i < 32; ++i) {
    cache->read_slot(buff_to + (i * 255), 255);
  }
  return NULL;
}

void *write_to_cache(void *args) {
  struct st_my_thread_var thdvar;
  set_mysys_var(&thdvar);
  pthread_barrier_wait(&barrier);
  int *v_args= (int *) args;
  for (int i= v_args[0]; i < v_args[1]; ++i)
    cache->write_slot(buff_from + (i * 255), 255);
  return NULL;
}

void *write_to_cache_one(void*) {
  for (int i= 0; i < 32; ++i)
    cache->write_slot(buff_from + (i * 255), 255);
  return NULL;
}

int main() {
  static const int thread_write_count= 4;
  static const int part_of_data_for_writers = 8;
  static const int size_buffer = 10000;

  clock_t tss, tee;
  int args[8];

  pthread_t thr_read;
  pthread_t *thr_write= (pthread_t *) malloc(8 * sizeof(pthread_t));

  buff_to= (uchar *) malloc(sizeof(uchar) * size_buffer);
  buff_from = (uchar*) malloc(sizeof(uchar) * size_buffer);
  pthread_barrier_init(&barrier, NULL, thread_write_count + 1);

  {
    std::ofstream off;
    off.open("random.txt");
    char c;
    int r;
    srand (0);
    for (int i=0; i<8160; i++) {
      r = i % 4;   // generate a random number
      if(r == 3) {
        buff_from[i] = '\n';
        continue;
      }
      c = 'a' + rand() % 26; // Convert to a character from a-z
      buff_from[i] = c;
    }
    off << buff_from; // copy generated bytes to file
  }

  remove("cache_file.txt"); // re-create cache file on each start

  tss= clock();

  cache= new RingBuffer((char *) "cache_file.txt", 4096);

  for (int i= 0; i < thread_write_count; ++i) {
    args[i * 2]= i * part_of_data_for_writers;
    args[(i * 2) + 1]= (i + 1) * part_of_data_for_writers;
    pthread_create(&thr_write[i], NULL, write_to_cache, (void *) &args[i * 2]);
  }

  pthread_create(&thr_read, NULL, read_to_cache, NULL);

  for (int i= 0; i < thread_write_count; ++i)
    pthread_join(thr_write[i], NULL);
  pthread_join(thr_read, NULL);

  delete cache;

  tee= clock();
  printf("Time: %lld\n", (long long) tee - tss);
  std::ofstream of;
  of.open("test_out.txt", std::ios_base::out);
  of << buff_to;
  return 0;
}