66 lines
1.7 KiB
C++
66 lines
1.7 KiB
C++
#include "Core/Threads.h"
|
|
#include <iostream>
|
|
#include <vector>
|
|
#include <cassert>
|
|
|
|
#ifdef __linux__
|
|
#include <pthread.h>
|
|
#include <sched.h>
|
|
#endif
|
|
|
|
using namespace uLib;
|
|
|
|
void TestThreadAffinity() {
|
|
std::cout << "Testing Thread Affinity..." << std::endl;
|
|
#ifdef __linux__
|
|
Thread t;
|
|
t.Start();
|
|
t.SetAffinity(0); // Bind to CPU 0
|
|
|
|
cpu_set_t cpuset;
|
|
CPU_ZERO(&cpuset);
|
|
pthread_getaffinity_np(t.GetNativeHandle(), sizeof(cpu_set_t), &cpuset);
|
|
assert(CPU_ISSET(0, &cpuset));
|
|
|
|
t.Join();
|
|
std::cout << " Passed (Thread bound to CPU 0)." << std::endl;
|
|
#else
|
|
std::cout << " Affinity not supported on this OS, skipping." << std::endl;
|
|
#endif
|
|
}
|
|
|
|
void TestTeamAffinity() {
|
|
std::cout << "Testing Team Affinity..." << std::endl;
|
|
#ifdef __linux__
|
|
#ifdef _OPENMP
|
|
Team team(2);
|
|
std::vector<int> cpus = {0, 1};
|
|
team.SetAffinity(cpus);
|
|
|
|
// We check affinity inside a parallel region
|
|
#pragma omp parallel
|
|
{
|
|
cpu_set_t cpuset;
|
|
CPU_ZERO(&cpuset);
|
|
pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
|
|
int tid = Thread::GetThreadNum();
|
|
int expected_cpu = cpus[tid % cpus.size()];
|
|
assert(CPU_ISSET(expected_cpu, &cpuset));
|
|
}
|
|
std::cout << " Passed (Team threads bound correctly)." << std::endl;
|
|
#endif
|
|
#else
|
|
std::cout << " Affinity not supported on this OS, skipping." << std::endl;
|
|
#endif
|
|
}
|
|
|
|
// Helper to get native handle if needed (oops, I forgot to add it to Thread class)
|
|
// I'll add GetNativeHandle() to Thread class in Threads.h
|
|
|
|
int main() {
|
|
TestThreadAffinity();
|
|
TestTeamAffinity();
|
|
std::cout << "All Affinity tests finished!" << std::endl;
|
|
return 0;
|
|
}
|