Parallel.For多久调用一次localInit? [英] How often does Parallel.For invoke localInit?
问题描述
我一直在尝试Parallel.For.特别是,支持诸如
I've been experimenting with Parallel.For. In particular, overloads that support thread-local data such as
公共静态System.Threading.Tasks.ParallelLoopResult For(长fromInclusive,长到Exclusive,System.Threading.Tasks.ParallelOptions parallelOptions,Func localInit,Func主体,Action localFinally);
public static System.Threading.Tasks.ParallelLoopResult For (long fromInclusive, long toExclusive, System.Threading.Tasks.ParallelOptions parallelOptions, Func localInit, Func body, Action localFinally);
根据文档
为参与循环执行的每个线程调用一次localInit委托
The localInit delegate is invoked once for each thread that participates in the loop's execution
但是我认为下面的例子与之矛盾
However I think my example below contradicts it
var threads = new ConcurrentBag<int>();
ValueTuple LocalInit()
{
threads.Add(Thread.CurrentThread.ManagedThreadId);
return new System.ValueTuple();
}
ValueTuple Body(long i, ParallelLoopState _, ValueTuple state)
{
Thread.Sleep(100);
return state;
}
void LocalFinally(ValueTuple state) { };
Parallel.For(0L, 1000L, new ParallelOptions(), LocalInit, Body, LocalFinally);
Console.WriteLine($"{threads.Count} inits between {threads.Distinct().Count()} threads");
它打印一条消息,例如
13个线程之间的79个初始化
79 inits between 13 threads
这是怎么回事?
推荐答案
尝试记录任务ID Task.CurrentId
,而不是线程ID.
Try recording task id Task.CurrentId
instead of thread id.
var threads = new ConcurrentBag<int>();
var tasks = new ConcurrentBag<int>();
ValueTuple LocalInit()
{
threads.Add(Thread.CurrentThread.ManagedThreadId);
tasks.Add(Task.CurrentId ?? throw new Exception());
return new System.ValueTuple();
}
ValueTuple Body(long i, ParallelLoopState _, ValueTuple state)
{
Thread.Sleep(100);
return state;
}
void LocalFinally(ValueTuple state) { };
Parallel.For(0L, 1000L, new ParallelOptions(), LocalInit, Body, LocalFinally);
Console.WriteLine($"{threads.Count} inits between {threads.Distinct().Count()} threads");
Console.WriteLine($"{tasks.Count} inits between {tasks.Distinct().Count()} tasks");
此打印
16个线程之间的87个初始化
87个任务之间的87个初始化
87 inits between 16 threads
87 inits between 87 tasks
该文档是错误的.他们应该改为
The docs are wrong. They should instead say
对参与循环执行的每个任务一次调用一次localInit委托
The localInit delegate is invoked once for each task that participates in the loop's execution
任务可能多于线程.总是线程数≤任务数≤迭代数.
There can be more tasks than threads. Always number of threads ≤ number of tasks ≤ number of iterations.
这篇关于Parallel.For多久调用一次localInit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!