okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4f5e6c841
main
1#pragma once 2 3#if defined(_WIN32 ) 4#ifndef WIN32_LEAN_AND_MEAN 5#define WIN32_LEAN_AND_MEAN 6#endif 7#include <windows.h> 8 9#include <cstdio> 10#include <cstddef> 11#include <vector> 12 13namespace strata::kernels::cpu::detail { 14 15// Hard affinity is only for pool-owned threads, which terminate with the pool. A caller's implicit 16// all-group affinity cannot be restored from PreviousGroupAffinity, so the host uses CPU Sets below. 17inline bool set_thread_group_affinity (int core ,int worker ) { 18if (core < 0 )return false; 19GROUP_AFFINITY target {}; 20target .Group = (WORD ) (core /64 ); 21target .Mask = KAFFINITY (1 ) << (core & 63 ); 22if (SetThreadGroupAffinity (GetCurrentThread (),& target ,nullptr ))return true; 23 std::fprintf (stderr ,"strata cpu pool: SetThreadGroupAffinity for worker %d (group %u, mask 0x%llx) failed: %lu; previous affinity kept\n" , 24worker , (unsigned )target .Group , (unsigned long long )target .Mask , (unsigned long )GetLastError ()); 25return false; 26} 27 28inline bool get_thread_cpu_sets (std::vector < ULONG >& ids ) { 29ULONG count = 0 ; 30if (!GetThreadSelectedCpuSets (GetCurrentThread (),nullptr ,0 ,& count )&& 31GetLastError ()!= ERROR_INSUFFICIENT_BUFFER )return false; 32ids .resize (count ); 33if (count == 0 )return true; 34if (!GetThreadSelectedCpuSets (GetCurrentThread (),ids .data (),count ,& count ))return false; 35ids .resize (count ); 36return true; 37} 38 39// CPU Set IDs are opaque: find the entry by both group and group-relative processor number. 40inline bool cpu_set_for_core (int core ,ULONG & id ) { 41ULONG bytes = 0 ; 42if (!GetSystemCpuSetInformation (nullptr ,0 ,& bytes ,GetCurrentProcess (),0 )&& 43GetLastError ()!= ERROR_INSUFFICIENT_BUFFER )return false; 44 std::vector < unsigned char > buffer (bytes ); 45if (bytes && !GetSystemCpuSetInformation (reinterpret_cast < PSYSTEM_CPU_SET_INFORMATION > (buffer .data ()), 46bytes ,& bytes ,GetCurrentProcess (),0 ))return false; 47constexpr size_t header_size = offsetof(SYSTEM_CPU_SET_INFORMATION ,CpuSet ); 48for (size_t offset = 0 ;offset + header_size <=bytes ;) { 49const auto * info = reinterpret_cast < const SYSTEM_CPU_SET_INFORMATION *> (buffer .data ()+ offset ); 50if (info -> Size < header_size || info -> Size > bytes - offset )break ; 51if (info -> Type == CpuSetInformation && info -> Size >=sizeof (SYSTEM_CPU_SET_INFORMATION )&& info -> CpuSet .Group == core /64 && 52info -> CpuSet .LogicalProcessorIndex == (core & 63 )&& 53 (!info -> CpuSet .Allocated || info -> CpuSet .AllocatedToTargetProcess )) { 54id = info -> CpuSet .Id ; 55return true; 56 } 57offset += info -> Size ; 58 } 59SetLastError (ERROR_NOT_FOUND ); 60return false; 61} 62 63}// namespace strata::kernels::cpu::detail 64#endif