-
Notifications
You must be signed in to change notification settings - Fork 0
/
TxRunner.h
66 lines (52 loc) · 1.06 KB
/
TxRunner.h
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
#pragma once
#include<thread>
#include"Database.h"
#include<functional>
#include"Transaction.h"
#include<map>
#include<mutex>
class TxRunner
{
public:
TxRunner(Database& db)
:db(db)
{
}
Database& get_db()
{
return db;
}
template <typename T>
void runTransactional(std::function<void(TxRunner* tx, int a, T b, Func_Name type)>& func, int a, T b)
{
int First_Commit = 0;
auto iter = map_.find(std::this_thread::get_id());
if (iter == map_.end())
{
++First_Commit;
std::lock_guard<std::mutex> ob(m);
Transaction obj(db, Read);
obj.start();
map_.insert({ std::this_thread::get_id(),obj });
}
auto iter2 = map_.find(std::this_thread::get_id());
try {
func(this, a, b, iter2->second.GetType());
}
catch (const std::runtime_error& error)
{
iter2->second.abort();
map_.erase(std::this_thread::get_id());
std::terminate();
}
if (First_Commit == 1)
{
iter2->second.commit();
map_.erase(std::this_thread::get_id());
}
}
private:
Database db;
std::map<std::thread::id, Transaction> map_;
std::mutex m;
};