-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiThreadTest.cpp
More file actions
107 lines (81 loc) · 2.41 KB
/
MultiThreadTest.cpp
File metadata and controls
107 lines (81 loc) · 2.41 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
#include <iostream>
#include <string>
#include <cassert>
#include <thread>
#include <chrono>
#include <sstream>
#include <mutex>
#include <locale>
#include "LogStore.h"
#include "LogIterator.h"
#include "./include/utils.h"
#include "./customBlob/StringBlob.h"
class ThreadTest {
private:
LogStore<StringBlob> *log_;
std::mutex lock_;
std::vector<std::vector<std::string>> out_;
public:
ThreadTest(LogStore<StringBlob> *log): log_(log) {}
void writeThread() {
for (uint64_t i = 1; i <= 100; i++) {
log_->Append(StringBlob(randomString(100) + IntToString(i)));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
}
void readThread() {
std::vector<std::string> records;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
for (LogIterator<StringBlob> itr = log_->Begin(); itr != log_->End(); itr++) {
records.push_back(*itr);
}
std::lock_guard<std::mutex> lock(lock_);
out_.push_back(records);
}
std::vector<std::vector<std::string>> get_out() const {
return std::move(out_);
}
};
bool checkReadData(std::vector<std::vector<std::string>> &&out) {
for (auto &vec : out) {
uint64_t prev_count = 0;
for (auto &e : vec) {
size_t pos = e.find_first_of("0123456789");
if (pos == std::string::npos) {
return false;
}
std::string counter = e.substr(pos, e.size() - pos);
uint64_t count = StringToInt(counter);
if (count <= prev_count) {
return false;
}
prev_count = count;
}
}
return true;
}
void multiThreadinTest() {
LogStore<StringBlob> log("MultiThread_TestLog");
ThreadTest t(&log);
std::vector<std::thread> workers;
// create write thread
workers.push_back(std::thread(&ThreadTest::writeThread, &t));
// create multiple read threads
for (uint64_t i = 0; i < 10; i++) {
workers.push_back(std::thread(&ThreadTest::readThread, &t));
}
// wait for all threads to finish
for (auto& thread : workers) {
thread.join();
}
// check read data
assert(checkReadData(t.get_out()) == true);
// empty log store
uint64_t pos = log.GetIndex();
log.Truncate(pos-1);
assert(log.GetSize() == 0);
}
int main() {
multiThreadinTest();
return 0;
}