I have lots of structure like below to make it support thread-safe version and unsafe version:
class NullMutex
{
public:
void lock() {}
void unlock() noexcept {}
bool try_lock() { return true; }
};
class IFoo
{
public:
virtual void DoSomething() = 0;
};
template<typename Mutex>
class Foo : public IFoo
{
Mutex m_Mutex;
public:
void DoSomething() override
{
std::lock_guard<Mutex> guard{ m_Mutex };
// ... some operations
}
};
using FooSt = Foo<NullMutex>; // Single thread
using FooMt = Foo<std::mutex>; // Multi-thread
int main()
{
std::shared_ptr<IFoo> foo{ new FooMt };
}
But as you can see, I must write all the implementation in a header file, and it also it increases my compilation time. The worst thing is it makes the classes that need to create it must have a template argument for choose the Mutex
type(then this class will also become a template and make the situation worse).
One of the solutions I've thought is to define a using Mutex = std::mutex
in a header file. But it needs to include this header file in every file in my project.
Is there a better way to solve this problem? Any suggestion will be really appreciated.