Files
spark/src/lib/utils/thread_manager.cpp
T
John Colvin 3b1a2357cc fix build (client): Change 'WIN32' macros to '_WIN32'
Not sure exactly how this broke, but the WIN32 macro is no longer defined.
2023-01-02 18:42:39 -05:00

118 lines
3.0 KiB
C++

#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 <boost/regex.hpp>
#include <fmt/format.h>
#ifndef _WIN32
#include <pthread.h>
#endif
namespace bts {
namespace threading {
config::ThreadGroupCfg get_thread_cfg(std::string const &name) {
for (auto const &cfg : config::get<config::Threads>().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<uint32_t> get_affinity(std::string const &name) {
std::vector<uint32_t> 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<void()> 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<void()> 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