Get thread id inside parallel.ForEach loop

Is there a way to find the thread id inside a Parallel.FoEach loop. I tried using var threadId = Thread.CurrentThread.ManagedThreadId - 1; but he did not give me the correct index i was looking for.

Here is a simple example:

 private void TestProgram() { int numThreads = 1; var values = new List<float>(); for (int i = 0; i < numThreads; ++i) { values.Add(i); } var data = new List<int>(); for (int i = 0; i < numThreads; ++i) { data.Add(i); } Parallel.ForEach(data, new ParallelOptions{MaxDegreeOfParallelism = numThreads}, i => //foreach (var i in data) { var threadId = Thread.CurrentThread.ManagedThreadId - 1; // make the index to start from 0 values[threadId] += i; }); } 

Even after setting MaxDegreeOfParallelism to 1 I still get threadId greater than 1.

Is there a way to find the thread id inside Parallel.ForEach in the above script?

Note. I could use Parallel.For in the example that I used. But my question is to find it inside Parallel.ForEach

+5
source share
4 answers

ThreadIDs are assigned by the base environment and are not guaranteed to be from 0 to [multiple threads] or even be consistent with the launch to run.

There are only a few contracts regarding thread identifiers, and even they are not guaranteed:

  • You will not get ThreadID 0
  • ThreadID 1 is usually reserved for the main thread
+5
source

Since Parallel.ForEach is part of the task library, Task.CurrentId will bring you closer to what you are looking for:

  var data = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; Parallel.ForEach(data, new ParallelOptions { MaxDegreeOfParallelism = 4 }, i => { Console.WriteLine(Task.CurrentId); }); 

- 1 1 1 1 1 1 1 1 1 1 2 2 1

However, there is a refusal in the documents:

Task identifiers are assigned on demand and do not necessarily represent the procedure for creating task instances. Please note that although collisions are very rare, task identifiers are not guaranteed to be unique.

+4
source

You will almost always get a thread id that is more than one. Concurrent operations will be scheduled in thread pool threads. Since these threads are created after the application has started, the thread ID has already been started.

0
source
 var data = new[] { 0,0,0,0,0,0,0,0,0,0,0,0,0}; Parallel.ForEach(data, new ParallelOptions{MaxDegreeOfParallelism = 10}, i => { Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId); }); 

I get the output:

180 180 180 180 180 180 180 180 180 62 62 62 62 180

This is typical. This is an environmental identifier and has little to do with your foreach loop. You can also see that in this case .NET did not feel the need to go up to MaxDegreeOfParallelism (which was another of your assumptions).

0
source

All Articles