forked from xiaopeifeng/CodeTricks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shared_ptr_copyonwrite.cc
59 lines (51 loc) · 1.03 KB
/
shared_ptr_copyonwrite.cc
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
#include <assert.h>
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
std::shared_ptr<int> kNumPtr(new int(0));
std::mutex kmtx;
std::shared_ptr<int> getSharedPtr()
{
kmtx.lock();
std::shared_ptr<int> ptr = kNumPtr;
kmtx.unlock();
return ptr;
}
void dosomething(std::shared_ptr<int> ptr)
{
std::cout << "value: " << *ptr << std::endl;
}
int main()
{
auto threadProc = [&](){
for(size_t i = 0; i < 100; ++i)
{
kmtx.lock();
if(!kNumPtr.unique()){
kNumPtr.reset(new int(*kNumPtr));
}
assert(kNumPtr.unique());
*kNumPtr = *kNumPtr + 1;
kmtx.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
};
std::thread t1(threadProc);
std::thread t2(threadProc);
std::thread t3(
[&](){
for(size_t i = 0; i < 100000; ++i)
{
std::shared_ptr<int> ptr = getSharedPtr();
dosomething(ptr);
}
}
);
t1.join();
t2.join();
t3.join();
std::cout << "kNumPtr's value: " << *kNumPtr << std::endl;
assert(*kNumPtr = 200);
assert(kNumPtr.unique());
}