NGen
Loading...
Searching...
No Matches
multithreading.hpp
1#ifndef NGEN_MULTITHREADING_HPP
2#define NGEN_MULTITHREADING_HPP
3
4#include <cstddef>
5#include <mutex>
6
8{
9 namespace details
10 {
11 // A string usable as a template argument, so that
12 // library_mutex() can be keyed by a library's name
13 template <std::size_t N>
15 constexpr string_literal(const char (&str)[N]) {
16 for (std::size_t i = 0; i < N; ++i)
17 value[i] = str[i];
18 }
19
20 char value[N];
21 };
22
23 // The one mutex in the process for the library named @arg
24 // name, created on first use. Exported, so that it stays one per
25 // process even if ngen is built as shared libraries with hidden
26 // visibility. Call library_mutex() rather than this.
27 [[gnu::visibility("default")]] std::mutex& named_library_mutex(char const* name);
28 }
29
30 // The mutex serializing calls into the library named @arg Name,
31 // which can't be called from more than one thread at a time. Every
32 // call into that library, anywhere in the process, must hold it:
33 //
34 // std::unique_lock netcdf_lock(multithreading::library_mutex<"netcdf">());
35 //
36 // "netcdf" is the NetCDF library, and the HDF5 library beneath it
37 // unless that was built thread-safe, which can't be called from more
38 // than one thread at a time even for different files.
39 //
40 // It's a plain std::mutex, so regions holding it must not nest.
41 //
42 // Each executable or shared library that calls this gets its own
43 // copy of the reference below, but they all refer to the one mutex
44 // that details::named_library_mutex() keeps for Name. A static
45 // mutex here instead would be one per shared library unless
46 // exported, which GCC won't do for a template specialized on a
47 // string_literal.
48 template <details::string_literal Name>
49 std::mutex& library_mutex()
50 {
51 static std::mutex& mutex = details::named_library_mutex(Name.value);
52 return mutex;
53 }
54}
55
56#endif // NGEN_MULTITHREADING_HPP
std::mutex & named_library_mutex(char const *name)
Definition multithreading.cpp:9
Definition multithreading.hpp:8
std::mutex & library_mutex()
Definition multithreading.hpp:49
Definition multithreading.hpp:14
char value[N]
Definition multithreading.hpp:20
constexpr string_literal(const char(&str)[N])
Definition multithreading.hpp:15