Validating CPU affinity across threads, SMT siblings and restarts

Validating CPU affinity across threads, SMT siblings and restarts

If latency still fluctuates after limiting a load test to two CPUs, the problem is often not that CPU pinning “doesn't work.” The affinity may have been changed only for the main thread, leaving worker threads on their original CPU set. Or the two selected CPU IDs may belong to the same physical core. On a dedicated server, validate CPU affinity thread by thread before assessing its effect on throughput and latency.

This walkthrough uses Ubuntu Server 24.04 LTS, taskset from util-linux, the system's procfs and sysfs interfaces, and an existing Python 3 installation. It starts only temporary processes, leaves live services unchanged, and does not assume that logical CPU IDs are consecutive.

1. Distinguish the allowed CPU set from the current execution location

CPU affinity specifies where a thread is allowed to run. It does not give the thread exclusive use of those CPUs or guarantee that it will keep them fully occupied. Other processes, kernel tasks, and interrupts can still run on the same core. Affinity is useful for narrowing the scheduler's choices and keeping experimental conditions consistent; it is not, by itself, a performance optimization.

First, record a baseline in the terminal from which you will launch the task:

uname -r
lscpu -e=CPU,ONLINE,SOCKET,CORE
grep '^Cpus_allowed_list:' /proc/self/status
taskset -pc $$

lscpu shows the machine's topology, while Cpus_allowed_list shows the CPU set the current thread is actually allowed to use. That set may already be restricted by a parent service or cpuset, so not every CPU present on the machine is necessarily an eligible target.

The PSR field in ps output is only the logical CPU on which a thread most recently ran, not its allowed set. A sample that happens to show a target CPU does not prove that the thread cannot migrate elsewhere later.

Validation answers two separate questions: is the thread restricted to the target set, and does the application perform better under that restriction? Confirm the first through scheduling attributes and the second by retesting with a fixed workload. A single screenshot of a thread's CPU location cannot replace either check.

2. Select cores by topology, not by consecutive CPU IDs

SMT exposes a physical core as multiple logical CPUs. To identify a physical core, consider both socket and core; comparing core_id alone is not enough. Use thread_siblings_list to see which logical CPUs share a core.

The following snippet selects one logical CPU from each of two different physical cores within the current allowed set. Copy it into the same Bash terminal and run it:

CPUS=$(python3 - <<'PY'
import os
from pathlib import Path

selected = []
seen = set()
for cpu in sorted(os.sched_getaffinity(0)):
    topology = Path(f"/sys/devices/system/cpu/cpu{cpu}/topology")
    key = (
        (topology / "physical_package_id").read_text().strip(),
        (topology / "core_id").read_text().strip(),
    )
    if key not in seen:
        seen.add(key)
        selected.append(cpu)
    if len(selected) == 2:
        break
if len(selected) != 2:
    raise SystemExit("Two eligible physical cores are required")
print(",".join(map(str, selected)))
PY
)
test -n "$CPUS" || exit 1
export CPUS
printf 'Selected CPUs: %s\n' "$CPUS"
for cpu in ${CPUS//,/ }; do
  cat "/sys/devices/system/cpu/cpu${cpu}/topology/thread_siblings_list"
done

This is a selection method for the exercise, not a recommendation for production CPU IDs. If another SMT thread on either selected core is already handling other work, the threads will still compete for core resources. To rule out that effect, also monitor the load on the sibling threads rather than adding more affinity options.

3. Verify the main thread, worker threads, and a later-created thread

On Linux, affinity is a per-thread attribute. New threads normally inherit their creator's mask, so applying the restriction at launch makes consistency easier than updating threads individually after the process has started. Applications that actively change their own affinity require separate checks.

Save the following file as affinity_probe.py. The program checks the main thread first, creates worker threads, and then creates another thread after a delay to simulate a thread pool expanding at runtime:

import os
import threading
import time

expected = {int(value) for value in os.environ["CPUS"].split(",")}
results = []
lock = threading.Lock()

def inspect():
    allowed = os.sched_getaffinity(0)
    with lock:
        results.append(allowed == expected)
        print(threading.get_native_id(), sorted(allowed), flush=True)
    time.sleep(15)

inspect_main = os.sched_getaffinity(0)
results.append(inspect_main == expected)
print(threading.get_native_id(), sorted(inspect_main), flush=True)

workers = [threading.Thread(target=inspect) for _ in range(2)]
for worker in workers:
    worker.start()
time.sleep(2)
late = threading.Thread(target=inspect)
late.start()
for worker in workers:
    worker.join()
late.join()
raise SystemExit(0 if all(results) else 1)

Launch it and inspect the process while it is still running:

taskset -c "$CPUS" python3 affinity_probe.py > affinity-result.txt &
PID=$!
sleep 3
taskset -apc "$PID"
grep -H '^Cpus_allowed_list:' /proc/"$PID"/task/*/status
wait "$PID"
RESULT=$?
cat affinity-result.txt
printf 'Exit status: %s\n' "$RESULT"

The sets in all four lines of program output should match the selected set, and the exit status should be zero. The fifteen-second delay is only an observation window for the experiment, not an application performance measurement. If the inspection commands run after the process exits, the task directory will no longer exist. Rerun the exercise rather than treating that as an affinity failure.

4. Include all threads when changing a running process

Running taskset -pc against the main PID of a running multithreaded program usually changes only the main thread. To update all existing threads, use taskset's -a option. However, traversing the threads is not an atomic operation on a continuously changing thread pool.

Before making a production change, establish whether the pool continually creates threads, whether it can pause accepting tasks, and whether the program sets affinity itself. If a live change is necessary, first save each thread's original CPU set. After the change, read every thread's status again, then trigger a path that expands the thread pool.

For a negative test, run the same probe without taskset in the test environment. If the terminal's allowed set is larger than the target set, the probe should exit with a nonzero status, demonstrating that the check detects the unrestricted state. If the sets already match, this test cannot distinguish the two states and does not count as a pass.

When retesting the application, keep the inputs, concurrency, and runtime configuration unchanged. Record throughput, latency percentiles, and CPU utilization. The pure Python thread probe validates scheduling attributes only; it is not intended to demonstrate multicore computing gains. Lower throughput after pinning can also be an expected consequence of reducing the CPU set available to the scheduler.

5. Revalidate after service restarts and keep a rollback path

Temporary taskset settings do not automatically become service configuration. For a service managed by systemd, confirm the actual unit name, then set CPUAffinity= in a dedicated drop-in. Use the CPU IDs verified earlier, separated by spaces.

This setting applies when the service starts; daemon-reload does not change existing threads. Schedule a restart that the application can accommodate, retrieve the new MainPID from systemctl show, and check it with taskset -apc. If the service also spawns multiple worker processes, include them in the checks rather than validating only the main process.

If AllowedCPUs= or a parent cpuset restriction is already in place, check its effective set as well. These restrictions also determine where a thread can ultimately run. Correct configuration text does not mean that the entire requested set is available. Recheck CPU IDs after changes to the hardware topology or CPU online status, too.

To roll back, remove only the affinity configuration added for this change, preserving the unit's other settings. Reload the configuration, restart the service, and read the actual CPU set again. The final record should include the topology, selected IDs, per-thread output, the new PID after restart, and application retest results. That evidence establishes both that the restriction reached the intended threads and that it is worth keeping.

Frequently asked questions

Does a successful taskset command bind every thread?

No. Targeting one PID in a running process normally changes only the corresponding thread. Use taskset -apc to inspect existing threads, then test whether newly created threads inherit the intended CPU set.

Do two logical CPUs always represent two physical cores?

No. They may be SMT siblings on the same core. Check physical_package_id, core_id and thread_siblings_list together. CPU affinity does not reserve those CPUs exclusively.

How can affinity be verified after a service restart?

Configure CPUAffinity for the actual service, obtain its new MainPID after restarting it, and inspect all worker threads. Neither the old PID nor the configuration file alone proves that the setting took effect.

AMD EPYC 7543P Dedicated Bare Metal Server

From $454/month

Configure a dedicated bare metal server for your workload

AMD EPYC 7543P servers are available with two memory options. The configuration page lists available add-ons and the amount due for the current billing period.