diff --git a/src/coreclr/gc/unix/gcenv.unix.cpp b/src/coreclr/gc/unix/gcenv.unix.cpp index 42b73e0611241a..61f144309cecf3 100644 --- a/src/coreclr/gc/unix/gcenv.unix.cpp +++ b/src/coreclr/gc/unix/gcenv.unix.cpp @@ -116,6 +116,9 @@ typedef cpuset_t cpu_set_t; // The cached total number of CPUs that can be used in the OS. uint32_t g_totalCpuCount = 0; +// The number of CPUs that are configured in the OS. +uint32_t g_configuredCpuCount = 0; + size_t GetRestrictedPhysicalMemoryLimit(); bool GetPhysicalMemoryUsed(size_t* val); @@ -158,6 +161,7 @@ bool GCToOSInterface::Initialize() } g_totalCpuCount = cpuCount; + g_configuredCpuCount = configuredCpuCount; if (!g_processAffinitySet.Initialize(configuredCpuCount)) { @@ -904,9 +908,16 @@ size_t GCToOSInterface::GetCacheSizePerLogicalCpu(bool trueSize) bool GCToOSInterface::SetThreadAffinity(uint16_t procNo) { #if HAVE_SCHED_SETAFFINITY || HAVE_PTHREAD_SETAFFINITY_NP - cpu_set_t cpuSet; - CPU_ZERO(&cpuSet); - CPU_SET((int)procNo, &cpuSet); + + size_t cpuSetSize = CPU_ALLOC_SIZE(g_configuredCpuCount); + cpu_set_t* pCpuSet = CPU_ALLOC(g_configuredCpuCount); + if (pCpuSet == nullptr) + { + return false; + } + + CPU_ZERO_S(cpuSetSize, pCpuSet); + CPU_SET_S((int)procNo, cpuSetSize, pCpuSet); // Snap's default strict confinement does not allow sched_setaffinity(, ...) without manually connecting the // process-control plug. sched_setaffinity(, ...) is also currently not allowed, only @@ -918,11 +929,13 @@ bool GCToOSInterface::SetThreadAffinity(uint16_t procNo) // - https://github.com/dotnet/runtime/issues/1634 // - https://forum.snapcraft.io/t/requesting-autoconnect-for-interfaces-in-pigmeat-process-control-home/17987/13 #if HAVE_SCHED_SETAFFINITY - int st = sched_setaffinity(0, sizeof(cpu_set_t), &cpuSet); + int st = sched_setaffinity(0, cpuSetSize, pCpuSet); #else - int st = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuSet); + int st = pthread_setaffinity_np(pthread_self(), cpuSetSize, pCpuSet); #endif + CPU_FREE(pCpuSet); + return (st == 0); #else // !(HAVE_SCHED_SETAFFINITY || HAVE_PTHREAD_SETAFFINITY_NP)