multithreading_test.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #ifndef MULTITHREADING_TEST_H
  2. #define MULTITHREADING_TEST_H
  3. #include "libbinom/include/file_storage/file_storage.h"
  4. #include <thread>
  5. using namespace binom;
  6. class PerfomanceTest {
  7. clock_t start_time;
  8. const char* msg;
  9. public:
  10. PerfomanceTest(const char* msg) : start_time(clock()), msg(msg) {}
  11. ~PerfomanceTest() {std::clog << msg << double( clock() - start_time ) / (double)CLOCKS_PER_SEC << " seconds." << std::endl;}
  12. };
  13. binom::DynamicStorage storage("mthr_test.db",
  14. varr{
  15. vobj{
  16. {"a", 1_ui8},
  17. {"b", 2_ui16},
  18. {"c", 4_ui32},
  19. {"d", 8_ui64},
  20. {"e", ui8arr{1,2,3}},
  21. {"f", ui16arr{4,5,6}},
  22. {"g", ui32arr{7,8,9}},
  23. {"h", ui64arr{10,11,12}},
  24. {"j", varr{1,2,3}}
  25. }
  26. }, false);
  27. void writer() {
  28. try{
  29. FileNodeVisitor node = storage;
  30. Variable var = vobj{
  31. {"a", 1_ui8},
  32. {"b", 2_ui16},
  33. {"c", 4_ui32},
  34. {"d", 8_ui64},
  35. {"e", ui8arr{1,2,3}},
  36. {"f", ui16arr{4,5,6}},
  37. {"g", ui32arr{7,8,9}},
  38. {"h", ui64arr{10,11,12}},
  39. {"j", varr{1,2,3}}
  40. };
  41. switch (rand()%3) {
  42. case 0:
  43. node.pushBack(var);
  44. std::clog << "\n\nPush back\n\n";
  45. return;
  46. case 1:
  47. node.pushFront(var);
  48. std::clog << "\n\nPush front\n\n";
  49. return;
  50. case 2:
  51. node.insert(node.getElementCount()/2, var);
  52. std::clog << "\n\nInsert to middle\n\n";
  53. return;
  54. }
  55. } catch(const Exception& except) {
  56. std::cerr << except.full() << '\n';
  57. std::terminate();
  58. }
  59. }
  60. void reader() {
  61. try {
  62. FileNodeVisitor node = storage;
  63. std::cout << node[rand()%node.getElementCount()].getVariable() << '\n';
  64. } catch (const Exception& except) {
  65. std::cerr << except.full() << '\n';
  66. std::terminate();
  67. }
  68. }
  69. #include <list>
  70. void file_storage_multithreading_test() {
  71. std::clog << "Start multithreading test\n";
  72. PerfomanceTest pt("End multithreading test: ");
  73. srand(time(nullptr));
  74. std::list<std::thread> threads;
  75. for(int i = 0; i < 5000; ++i) {
  76. threads.emplace_back(reader);
  77. threads.emplace_back(writer);
  78. }
  79. for(std::thread& thr : threads)
  80. thr.join();
  81. // std::clog << "Result: " << storage.getRoot().getVariable() << '\n';
  82. }
  83. #endif // MULTITHREADING_TEST_H