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