首先,您需要一些线程安全:
template<class T, class M=std::shared_timed_mutex> // shared_mutex in C++17
struct mutex_guarded {
template<class F>
auto write( F&& f )
->std::decay_t<std::result_of_t<F(T&)>> {
auto l = lock();
return std::forward<F>(f)(t);
}
template<class F>
auto read( F&& f ) const
->std::decay_t<std::result_of_t<F(T const&)>> {
auto l = lock();
return std::forward<F>(f)(t);
}
mutex_guarded() {}
template<class T0, class...Ts,
std::enable_if_t<!std::is_same<std::decay_t<T0>, mutex_guarded>{},int> =0
>
mutex_guarded(T0&& t0, Ts&&...ts):
t(std::forward<T0>(t0), std::forward<Ts>(ts)...)
{}
mutex_guarded( mutex_guarded const& o ):
t(o.copy_from())
{}
mutex_guarded( mutex_guarded && o ):
t(o.move_from())
{}
mutex_guarded& operator=(mutex_guarded const&)=delete;
mutex_guarded& operator=(mutex_guarded &&)=delete;
mutex_guarded& operator=(T const& t) {
write([&t](T& dest){dest=t;});
return *this;
}
mutex_guarded& operator=(T&& t) {
write([&t](T& dest){dest=std::move(t);});
return *this;
}
private:
T copy_from() const& { return read( [](T const& t){ return t; } ); }
T copy_from() && { return move_from(); }
T move_from() { return write( [](T& t){ return std::move(t); } ); }
std::unique_lock<M> lock() const {
return std::unique_lock<M>(m);
}
std::shared_lock<M> lock() {
return std::shared_lock<M>(m);
}
M m; // mutex
T t;
};
这让我们有一个:
using foo_factory = std::function<std::unique_ptr<Foo>()>;
using foo_factories = std::unordered_map<std::string, foo_factory>;
mutex_guarded<foo_factories>& get_foo_factories() {
static mutex_guarded<foo_factories> map;
return map;
}
它具有线程安全初始化,然后
void registerFoo(std::string name, std::function<Foo *()> factory)
{
get_foo_factories().write([](auto& f){f.emplace(name, factory);});
}
是线程安全的,并保证足够早地初始化工厂。
在停工时,工厂被摧毁的时间既超出了你的控制(建设顺序相反),也可能为时过早。
mutex_guarded<foo_factories>*& get_foo_factories() {
static auto* map = new mutex_guarded<foo_factories>;
return map;
}
void registerFoo(std::string name, std::function<Foo *()> factory)
{
get_foo_factories()->write([](auto& f){f.emplace(name, factory);});
}
void end_foo_factories() {
auto*& ptr = get_foo_factories();
delete ptr; ptr = nullptr;
}
这将把它放在堆上它会活得更久。请注意,这也会泄露工厂和地图;可以添加“足够晚”的手动销毁。请注意,这种销毁不是线程安全的,也不能廉价地使其成为线程安全的;它应该在所有线程都被清理之后发生。