Created
April 1, 2024 22:39
-
-
Save normanlmfung/3ac0f0d66f1a3fca34a2839b03a28cc3 to your computer and use it in GitHub Desktop.
csharp_thread_start_processor_affinity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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