1 /*
2    BAREOS® - Backup Archiving REcovery Open Sourced
3 
4    Copyright (C) 2019-2019 Bareos GmbH & Co. KG
5 
6    This program is Free Software; you can redistribute it and/or
7    modify it under the terms of version three of the GNU Affero General Public
8    License as published by the Free Software Foundation and included
9    in the file LICENSE.
10 
11    This program is distributed in the hope that it will be useful, but
12    WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14    Affero General Public License for more details.
15 
16    You should have received a copy of the GNU Affero General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19    02110-1301, USA.
20 */
21 
22 #ifndef BAREOS_SRC_LIB_THREAD_SPECIFIC_DATA_KEY_H_
23 #define BAREOS_SRC_LIB_THREAD_SPECIFIC_DATA_KEY_H_
24 
25 #include "lib/berrno.h"
26 
27 #include <mutex>
28 
29 class ThreadSpecificDataKey {
30  public:
Key()31   static pthread_key_t Key()
32   {
33     init_once();
34     return key_;
35   }
36 
37  private:
38   static pthread_key_t key_;
39   static std::once_flag once_flag;
40 
init_once()41   static void init_once()
42   {
43     try {
44       static std::once_flag once_flag;
45       std::call_once(once_flag, CreateKey);
46     } catch (const std::system_error& e) {
47       Jmsg1(nullptr, M_ABORT, 0,
48             _("Could not call CreateThreadSpecificDataKey: %s\n"), e.what());
49     }
50   }
51 
CreateKey()52   static void CreateKey()
53   {
54     int status = pthread_key_create(&key_, nullptr);
55     if (status != 0) {
56       BErrNo be;
57       Jmsg1(nullptr, M_ABORT, 0, _("pthread key create failed: ERR=%s\n"),
58             be.bstrerror(status));
59     }
60   }
61 };
62 
63 pthread_key_t ThreadSpecificDataKey::key_;
64 
65 #endif  // BAREOS_SRC_LIB_THREAD_SPECIFIC_DATA_KEY_H_
66