Line data Source code
1 : // Copyright (c) 2013-2022 Made to Order Software Corp. All Rights Reserved
2 : //
3 : // https://snapwebsites.org/project/snaplogger
4 : // contact@m2osw.com
5 : //
6 : // This program is free software; you can redistribute it and/or modify
7 : // it under the terms of the GNU General Public License as published by
8 : // the Free Software Foundation; either version 2 of the License, or
9 : // (at your option) any later version.
10 : //
11 : // This program is distributed in the hope that it will be useful,
12 : // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 : // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 : // GNU General Public License for more details.
15 : //
16 : // You should have received a copy of the GNU General Public License along
17 : // with this program; if not, write to the Free Software Foundation, Inc.,
18 : // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 :
20 : /** \file
21 : * \brief Create a guard in all functions that need to run on their own.
22 : *
23 : * This library is thread safe. It uses one mutex to guard any access
24 : * which requires safe access:
25 : *
26 : * \code
27 : * {
28 : * guard g;
29 : *
30 : * ...do multi-thread safe work...
31 : * }
32 : * \endcode
33 : */
34 :
35 : // self
36 : //
37 : #include "snaplogger/guard.h"
38 :
39 :
40 : // cppthread lib
41 : //
42 : #include <cppthread/guard.h>
43 : #include <cppthread/mutex.h>
44 :
45 :
46 : // last include
47 : //
48 : #include <snapdev/poison.h>
49 :
50 :
51 :
52 : namespace snaplogger
53 : {
54 :
55 :
56 :
57 : namespace
58 : {
59 :
60 :
61 :
62 : cppthread::mutex * g_mutex = nullptr;
63 :
64 :
65 :
66 : }
67 : // no name namespace
68 :
69 :
70 :
71 :
72 :
73 1212319 : guard::guard()
74 : {
75 : {
76 : // we know for sure that g_system_mutex was already initialized
77 : // so we can use it here
78 : //
79 2424638 : cppthread::guard lock(*cppthread::g_system_mutex);
80 :
81 1212319 : if(g_mutex == nullptr)
82 : {
83 2 : g_mutex = new cppthread::mutex;
84 : }
85 : }
86 :
87 1212319 : g_mutex->lock();
88 1212319 : }
89 :
90 :
91 1212319 : guard::~guard()
92 : {
93 1212319 : g_mutex->unlock();
94 1212319 : }
95 :
96 :
97 :
98 : } // snaplogger namespace
99 : // vim: ts=4 sw=4 et
|