Mind: Distribute and pin Mind threads to CPUs
At startup, Marionette will distribute and pin the Mind threads across the available CPUs, warning if it couldn't do so.
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
#include <iostream>
|
||||
#include <componentThread.h>
|
||||
#include <boost/asio.hpp>
|
||||
#include <pthread.h>
|
||||
#include <sched.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace smo {
|
||||
|
||||
@@ -382,4 +385,72 @@ void ComponentThread::exceptionInd(ComponentThread& thread)
|
||||
});
|
||||
}
|
||||
|
||||
// CPU management method implementations
|
||||
int ComponentThread::getAvailableCpuCount()
|
||||
{
|
||||
int cpuCount = sysconf(_SC_NPROCESSORS_ONLN);
|
||||
if (cpuCount <= 0)
|
||||
{
|
||||
throw std::runtime_error(std::string(__func__)
|
||||
+ ": Failed to determine CPU count");
|
||||
}
|
||||
|
||||
// Check if std::thread::hardware_concurrency() matches sysconf result
|
||||
unsigned int hwConcurrency = std::thread::hardware_concurrency();
|
||||
if (hwConcurrency != static_cast<unsigned int>(cpuCount))
|
||||
{
|
||||
std::cerr << "Warning: CPU count mismatch - "
|
||||
"std::thread::hardware_concurrency() = "
|
||||
<< hwConcurrency << ", sysconf(_SC_NPROCESSORS_ONLN) = "
|
||||
<< cpuCount << "\n";
|
||||
}
|
||||
|
||||
return cpuCount;
|
||||
}
|
||||
|
||||
void ComponentThread::pinToCpu(int cpuId)
|
||||
{
|
||||
if (cpuId < 0)
|
||||
{
|
||||
throw std::runtime_error(std::string(__func__)
|
||||
+ ": Invalid CPU ID: " + std::to_string(cpuId));
|
||||
}
|
||||
|
||||
cpu_set_t cpuset;
|
||||
CPU_ZERO(&cpuset);
|
||||
CPU_SET(cpuId, &cpuset);
|
||||
|
||||
int result = pthread_setaffinity_np(
|
||||
thread.native_handle(), sizeof(cpu_set_t), &cpuset);
|
||||
if (result != 0)
|
||||
{
|
||||
throw std::runtime_error(std::string(__func__)
|
||||
+ ": Failed to pin thread to CPU " + std::to_string(cpuId)
|
||||
+ ": " + std::strerror(result));
|
||||
}
|
||||
|
||||
pinnedCpuId = cpuId;
|
||||
std::cout << name << ": Pinned to CPU " << cpuId << "\n";
|
||||
}
|
||||
|
||||
void ComponentThread::distributeAndPinThreadsAcrossCpus()
|
||||
{
|
||||
int cpuCount = getAvailableCpuCount();
|
||||
std::cout << "Available CPUs: " << cpuCount << "\n";
|
||||
|
||||
// Skip the marionette thread (MRNTT) as it's the control thread
|
||||
int threadIndex = 0;
|
||||
for (auto& thread : componentThreads)
|
||||
{
|
||||
if (thread->id == MRNTT) { continue; }
|
||||
|
||||
int targetCpu = threadIndex % cpuCount;
|
||||
thread->pinToCpu(targetCpu);
|
||||
++threadIndex;
|
||||
}
|
||||
|
||||
std::cout << "Distributed " << (threadIndex) << " threads across "
|
||||
<< cpuCount << " CPUs\n";
|
||||
}
|
||||
|
||||
} // namespace smo
|
||||
|
||||
Reference in New Issue
Block a user