#include "thread_manager.h" #include "lib/config/config.h" #include "lib/config/protos/threads.pb.h" #include "lib/logging/logging.h" #include "lib/utils/bts_assert.h" #include #include #ifndef _WIN32 #include #endif namespace bts { namespace threading { config::ThreadGroupCfg get_thread_cfg(std::string const &name) { for (auto const &cfg : config::get().thread_group()) { boost::regex rx(cfg.name_rx()); if (boost::regex_match(name, rx)) return cfg; } bts_assert_msg( false, fmt::format("No configuration found for thread {}", name)); } std::vector get_affinity(std::string const &name) { std::vector result; #ifndef _WIN32 auto cfg = get_thread_cfg(name); if (cfg.exclude()) { auto total_cpus = sysconf(_SC_NPROCESSORS_ONLN); for (int i = 0; i < total_cpus; i++) if (std::find(cfg.core().begin(), cfg.core().end(), i) == cfg.core().end()) result.push_back(i); } else { for (auto const &core : cfg.core()) result.push_back(core); } #endif return result; } #ifndef _WIN32 void configure_thread( std::string const &name, config::ThreadGroupCfg const &cfg, pthread_t t) { if (cfg.core().size()) { cpu_set_t cpuset; CPU_ZERO(&cpuset); if (cfg.exclude()) { auto total_cpus = sysconf(_SC_NPROCESSORS_ONLN); for (int i = 0; i < total_cpus; i++) CPU_SET(i, &cpuset); for (auto const &core : cfg.core()) CPU_CLR(core, &cpuset); } else { for (auto const &core : cfg.core()) CPU_SET(core, &cpuset); } int rc = pthread_setaffinity_np(t, sizeof(cpu_set_t), &cpuset); if (rc != 0) LOG(Gen, Error, "Could not set core affinity for {} on thread {}. Error " "code={}", name, cfg.name_rx(), rc); } } #endif void configure_current_thread(std::string const &name) { #ifndef _WIN32 configure_thread(name, get_thread_cfg(name), pthread_self()); #endif os::set_thread_name(name); } void configure_current_thread( std::string const &name, config::ThreadGroupCfg const &cfg) { #ifndef _WIN32 configure_thread(name, cfg, pthread_self()); #endif os::set_thread_name(name); } std::thread make_thread_from_function( std::string const &name, std::function const &c) { auto result = std::thread([c, name]() { os::set_thread_name(name); c(); }); #ifndef _WIN32 configure_thread(name, get_thread_cfg(name), result.native_handle()); #endif return result; } std::thread make_thread_from_function( std::string const &name, std::function const &c, config::ThreadGroupCfg const &cfg) { auto result = std::thread([c, name]() { os::set_thread_name(name); c(); }); #ifndef _WIN32 configure_thread(name, cfg, result.native_handle()); #endif return result; } } // namespace threading } // namespace bts