-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_lock.cpp
97 lines (77 loc) · 1.42 KB
/
file_lock.cpp
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
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/file.h>
#include <mutex>
#include <thread>
#include <iostream>
#include <chrono>
using namespace std::chrono;
class mutex_locker
{
public:
mutex_locker() = default;
int lock()
{
mutex_.lock();
return 0;
}
int unlock()
{
mutex_.unlock();
return 0;
}
private:
std::mutex mutex_;
};
class locker
{
public:
locker()
{
fd_ = open("lock.lock", O_CREAT | O_EXCL, 0777);
fd_ = open("lock.lock", O_RDWR );
}
int lock()
{
int ret;
ret = flock(fd_, LOCK_EX);
return 0;
}
int unlock()
{
int ret;
ret = flock(fd_, LOCK_UN);
return ret;
}
private:
int fd_;
};
int start = 0;
long long sum = 0;
mutex_locker l;
void foo()
{
while(!start)
;
auto tic = std::chrono::high_resolution_clock::now();
for (int i=0; i<=100000; ++i)
{
l.lock();
sum += i;
l.unlock();
}
auto toc = std::chrono::high_resolution_clock::now();
auto dur = duration_cast<milliseconds>(toc - tic);
std::cout<< dur.count()<< std::endl;
}
int main(int argc,char *argv[])
{
start = 0;
std::thread t1(foo);
std::thread t2(foo);
start = 1;
t1.join();
t2.join();
printf("sum=%lld\n", sum);
}