I want to share this code, showing how to do it with TPL.
With threads,
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();
}
With TPL (Below code will not work, just a failed attempt),
using System;
using System.Diagnostics;
using System.Threading.Tasks;
int processorCount = Environment.ProcessorCount;
Task[] tasks = new Task[processorCount];
for (int i = 0; i < processorCount; i++)
{
int processorNum = i;
tasks[i] = Task.Factory.StartNew(() => Fibonacci(processorNum * 10), TaskCreationOptions.LongRunning);
}
// Set processor affinity for each task
ProcessThreadCollection currentThreads = Process.GetCurrentProcess().Threads;
for (int i = 0; i < processorCount; i++)
{
ProcessThread assignedThread = null;
foreach (ProcessThread thread in currentThreads)
{
# Problem here: Is possible to find out TPL task's thread ID, after it started? And then assign processor affinity after startNew?
if (thread.Id == tasks[i].Id)
{
assignedThread = thread;
break;
}
}
if (assignedThread != null)
{
int processorNum = i;
assignedThread.ProcessorAffinity = (IntPtr)(1 << processorNum);
}
}
Task.WaitAll(tasks);
Console.ReadLine();