-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathraii.cpp
More file actions
134 lines (111 loc) · 2.16 KB
/
raii.cpp
File metadata and controls
134 lines (111 loc) · 2.16 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <stdlib.h>
using namespace std;
const int maxInput = 1000;
using boost::mutex;
using boost::thread;
class Users {
private:
vector<string> userList;
public:
Users (int max)
{
userList = vector<string> (max);
}
void Add (string user)
{
userList.push_back (user);
}
bool Search (string user)
{
for (vector<string>::iterator it = userList.begin (); it != userList.end (); it++)
{
if (*it == user)
return true;
}
return false;
}
~Users ()
{
}
};
string strings [] = {"one", "two", "three","four","five","six","seven","eight","nine","ten"};
static void
useradd_thread (Users &usrs, int max, mutex *mtx)
{
for (int i =0; i < max; i++)
{
mtx->lock ();
usrs.Add(strings[rand()%10]);
mtx->unlock ();
}
}
class NonCopyable
{
NonCopyable (NonCopyable &noncopy);
NonCopyable & operator= (NonCopyable const &noncopy);
public:
NonCopyable ()
{
}
};
class AutoLock : private NonCopyable
{
private:
mutex *lock;
public:
AutoLock (mutex *mtx):lock(mtx)
{
lock->lock();
cout << "Locked using the AutoLock" << endl;
}
~AutoLock ()
{
lock->unlock();
cout << "UnLocked using the AutoLock" << endl;
}
};
class AutoDelete : private NonCopyable
{
private:
string **temp;
public:
AutoDelete (string **t):temp(t)
{
}
~AutoDelete ()
{
cout << "Auto deleting the string " << endl;
delete *temp;
*temp = NULL;
}
};
static bool
user_search (Users &usrs, string usr, mutex *mtx)
{
AutoLock Lock(mtx);
return usrs.Search (usr);
}
int
main ()
{
Users usrs(maxInput);
mutex mtx;
string *usrSearch = new string ("six");
// Deallocate the memory once we get out of scope
// Similar strategy can be used for file descriptors as well
AutoDelete deferedDelete(&usrSearch);
thread th1 (useradd_thread, usrs, maxInput, &mtx);
bool result = user_search (usrs, *usrSearch, &mtx);
if (result)
cout << "Found the user " << *usrSearch << " " << endl;
else
cout << "Could not find the user " << *usrSearch << " " << endl;
th1.join ();
return 0;
}