LibreOffice Module comphelper (master)  1
doublecheckedinit.hxx
Go to the documentation of this file.
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3  * This file is part of the LibreOffice project.
4  *
5  * This Source Code Form is subject to the terms of the Mozilla Public
6  * License, v. 2.0. If a copy of the MPL was not distributed with this
7  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8  *
9  * This file incorporates work covered by the following license notice:
10  *
11  * Licensed to the Apache Software Foundation (ASF) under one or more
12  * contributor license agreements. See the NOTICE file distributed
13  * with this work for additional information regarding copyright
14  * ownership. The ASF licenses this file to you under the Apache
15  * License, Version 2.0 (the "License"); you may not use this file
16  * except in compliance with the License. You may obtain a copy of
17  * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18  */
19 
20 #ifndef INCLUDED_COMPHELPER_DOUBLECHECKEDINIT_HXX
21 #define INCLUDED_COMPHELPER_DOUBLECHECKEDINIT_HXX
22 
23 #include <osl/getglobalmutex.hxx>
24 
25 #include <atomic>
26 // HACK: <atomic> includes <stdbool.h>, which in some Clang versions does '#define bool bool',
27 // which confuses clang plugins.
28 #undef bool
29 #include <functional>
30 
31 namespace comphelper
32 {
41 template <typename Type, typename Function = std::function<Type*()>,
42  typename Guard = osl::MutexGuard, typename GuardCtor = osl::GetGlobalMutex>
43 static inline Type* doubleCheckedInit(std::atomic<Type*>& pointer, Function function,
44  GuardCtor guardCtor = osl::GetGlobalMutex())
45 {
46  Type* p = pointer.load(std::memory_order_acquire);
47  if (!p)
48  {
49  Guard guard(guardCtor());
50  p = pointer.load(std::memory_order_relaxed);
51  if (!p)
52  {
53  p = function();
54  pointer.store(p, std::memory_order_release);
55  }
56  }
57  return p;
58 }
59 
60 } // namespace
61 
62 #endif // INCLUDED_COMPHELPER_DOUBLECHECKEDINIT_HXX
63 
64 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
Type
static Type * doubleCheckedInit(std::atomic< Type * > &pointer, Function function, GuardCtor guardCtor=osl::GetGlobalMutex())
Thread-safe singleton creation.