I am interacting with a C library, whose documentation states that certain functions are not thread safe. Since its functions deal heterogeneously with multiple types, I have written a template wrapper to use it in a homogeneous manner from C++. However, I now need to ensure serialized access to certain functions, serialized across all instantiated template wrappers.
I believe the following approach should work; what I would like to know is, are there any caveats to the following approach, and if so, what are they and how can I get around them?
struct LibMutexPolicy
{
static std::mutex & getMutexInstance()
{
static std::mutex inst;
return inst;
}
};
template <typename T>
struct A : private LibMutexPolicy
{
void foo()
{
std::lock_guard<std::mutex> lock(getMutexInstance());
// Call non thread-safe library code
}
};