Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save normanlmfung/3ac0f0d66f1a3fca34a2839b03a28cc3 to your computer and use it in GitHub Desktop.
Save normanlmfung/3ac0f0d66f1a3fca34a2839b03a28cc3 to your computer and use it in GitHub Desktop.
csharp_thread_start_processor_affinity
// https://stackoverflow.com/questions/2510593/how-can-i-set-processor-affinity-to-a-thread-or-a-task-in-net
using System;
using System.Diagnostics;
using System.Threading;
static void Fibonacci(int n)
{
int a = 0, b = 1, c = 0;
for (int i = 0; i < n; i++)
{
c = a + b;
a = b;
b = c;
}
Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId}: Fibonacci({n}) = {c}");
}
int processorCount = Environment.ProcessorCount;
for (int i = 0; i < processorCount; i++)
{
int processorNum = i;
Thread thread = new Thread(() => Fibonacci(processorNum * 10));
// Set processor affinity for each thread
thread.ProcessorAffinity = (IntPtr)(1 << processorNum);
thread.Start();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment