c++ - 在 c++ 中,任何仅在写入时导致主要开销的跨线程同步方法?
问题描述
我想构建提供线程本地资源查找的调度系统。
查找的读取频率很高,但仅在添加新线程时才会更新。
使用atomic
/mutex
对读写造成相当大的开销。
有什么办法可以将开销转移到写入和快速读取?
例如,查找asio::io_context
class Foo {
public:
static Foo* instance;
std::unordered_map<int/*custom thread id*/, asio::io_context* > io_contexts
};
enum class threads:int{
network, file_io, others_that_may_spawn_after_init_phase...
};
void some_func_called_in_random_thread() {
//need an unwanted lock here
asio::post(Foo::instance->io_contexts[threads::network], xxx);
asio::post(Foo::instance->io_contexts[threads::file_io], yyy);
}
void init_network(){
auto ptr = new asio::io_contexts();
//need a lock here
Foo::instance->io_contexts[trd_network] = ptr;
}
...