CPU Affinity

This commit is contained in:
Christopher Taylor 2017-06-05 02:04:10 -07:00
parent 5dac73a085
commit 73a58a21b1
2 changed files with 37 additions and 5 deletions

View File

@ -436,10 +436,12 @@ void VectorXOR(
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// WorkerThread // WorkerThread
void WorkerThread::Start() void WorkerThread::Start(unsigned cpu_affinity)
{ {
Stop(); Stop();
CPUAffinity = cpu_affinity;
#ifdef _WIN32 #ifdef _WIN32
hEvent = ::CreateEventW(nullptr, FALSE, FALSE, nullptr); hEvent = ::CreateEventW(nullptr, FALSE, FALSE, nullptr);
#endif #endif
@ -485,8 +487,26 @@ void WorkerThread::Wake()
#endif #endif
} }
static bool SetCurrentThreadAffinity(unsigned processorIndex)
{
#ifdef _WIN32
return 0 != ::SetThreadAffinityMask(
::GetCurrentThread(), (DWORD_PTR)1 << (processorIndex & 63));
#elif !defined(ANDROID)
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(processorIndex, &cpuset);
return 0 == pthread_setaffinity_np(pthread_self(),
sizeof(cpu_set_t), &cpuset);
#else
return true; // FIXME: Unused on Android anyway
#endif
}
void WorkerThread::Loop() void WorkerThread::Loop()
{ {
SetCurrentThreadAffinity(CPUAffinity);
for (;;) for (;;)
{ {
if (Terminated) if (Terminated)
@ -572,7 +592,7 @@ WorkerPool::WorkerPool()
Workers = new WorkerThread[WorkerCount]; Workers = new WorkerThread[WorkerCount];
for (unsigned i = 0; i < WorkerCount; ++i) for (unsigned i = 0; i < WorkerCount; ++i)
Workers[i].Start(); Workers[i].Start(i);
std::atexit(AtExitWrapper); std::atexit(AtExitWrapper);
} }
@ -597,8 +617,17 @@ void WorkerPool::Dispatch(WorkBundle* bundle, const WorkerCallT& call)
void WorkerPool::Run() void WorkerPool::Run()
{ {
unsigned remaining;
{
Locker locker(QueueLock);
remaining = Remaining;
}
unsigned count = WorkerCount;
if (count > remaining)
count = remaining;
// Wake all the workers // Wake all the workers
for (unsigned i = 0, count = WorkerCount; i < count; ++i) for (unsigned i = 0; i < count; ++i)
Workers[i].Wake(); Workers[i].Wake();
DrainWorkQueue(); DrainWorkQueue();

View File

@ -557,17 +557,20 @@ private:
class WorkerThread class WorkerThread
{ {
public: public:
WorkerThread() {} WorkerThread()
{
}
~WorkerThread() ~WorkerThread()
{ {
Stop(); Stop();
} }
void Start(); void Start(unsigned cpu_affinity);
void Stop(); void Stop();
void Wake(); void Wake();
protected: protected:
unsigned CPUAffinity = 0;
std::atomic_bool Terminated = false; std::atomic_bool Terminated = false;
std::unique_ptr<std::thread> Thread; std::unique_ptr<std::thread> Thread;