blob: 95796e6f94a2480fb5bd92eaa3b170d2779a6ef1 (
plain)
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
|
<html>
<head>
<title>Apache Qpid : ScopedLocking</title>
<link rel="stylesheet" href="styles/site.css" type="text/css" />
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<table class="pagecontent" border="0" cellpadding="0" cellspacing="0" width="100%" bgcolor="#ffffff">
<tr>
<td valign="top" class="pagebody">
<div class="pageheader">
<span class="pagetitle">
Apache Qpid : ScopedLocking
</span>
</div>
<div class="pagesubheading">
This page last changed on Oct 19, 2006 by <font color="#0050B2">mmccorma</font>.
</div>
<p>Always use scoped lockers to lock mutexes and the like. Don't do this:</p>
<div class="preformatted"><div class="preformattedContent">
<pre> lock.acquire();
do_stuff(); // DANGER: lock never released if exception thrown here.
lock.release();
</pre>
</div></div>
<p>Instead use a "scoped locker". This is simply a class that does the "acquire" in its constructor and the "release" in its destructor:</p>
<div class="preformatted"><div class="preformattedContent">
<pre> Locker locker(lock);
do_stuff();
</pre>
</div></div>
<p>Not only does this save a bit of typing, it guarantees that the lock will be released even if an exception is thrown, because C++ guarantees to call destructors of all local variables on exit from a scope. This also protects you forgetting to release the lock at every exit point from a function with multiple exit points - the compiler takes care of it for you. This technique applies more generally to any situation where you have to acquire and release resources. <tt>std::auto_ptr</tt> is a similar tool for memory management.</p>
</td>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td height="12" background="border/border_bottom.gif"><img src="border/spacer.gif" width="1" height="1" border="0"/></td>
</tr>
<tr>
<td align="center"><font color="grey">Document generated by Confluence on Apr 22, 2008 02:47</font></td>
</tr>
</table>
</body>
</html>
|