本地队列中的子任务
Subtasks in Local Queue
当我读到 Colin Campbell 写的一本关于并行编程的书时,我看到了以下几行:
When one of the task factory methods is called from within a thread
pool worker thread, the default task scheduler places the new task in
that thread’s local task queue. This is a faster operation than
placing it in the global queue.
根据我从上一段中推断出的内容,我编写了以下代码,认为所有任务都将由同一个工作线程执行,因为它在书中进一步写道:
any time you create a task from within another task or from within a
thread pool work item, you are performing an operation that is part of
some larger computation
Task.Factory.StartNew(() =>
{
Thread.Sleep(1000);
Console.WriteLine("Task Id for A task: {0}", Thread.CurrentThread.ManagedThreadId);
// subtasks within Global Task
var t2 = Task.Factory.StartNew(() => { Thread.Sleep(500); Console.WriteLine("Task Id for B task : {0}", Thread.CurrentThread.ManagedThreadId); });
var t3 = Task.Factory.StartNew(() => { Thread.Sleep(1000); Console.WriteLine("Task Id for C task: {0}", Thread.CurrentThread.ManagedThreadId); });
var t4 = Task.Factory.StartNew(() => { Thread.Sleep(2000); Console.WriteLine("Task Id for D task: {0}", Thread.CurrentThread.ManagedThreadId); });
Task.WaitAll(t2, t3, t4);
});
但是出乎我的意料,结果竟然是:
结果:
任务的任务 ID:1
B 任务的任务 ID:2
D 任务的任务 ID:4
C 任务的任务 ID:3
期望:
任务的任务 ID:1
B 任务的任务 ID:1
D 任务的任务 ID:1
C 任务的任务 ID:1
看来我的直觉误导了我!我在哪里丢失了曲目?
您忘记了窃取工作,它很可能与您的第一个报价位于同一部分。如果您删除 sleeps 和 WaitAll,您会得到什么结果。还有 task Id != thread Id 你正在检查错误的值以查看线程共享。
当我读到 Colin Campbell 写的一本关于并行编程的书时,我看到了以下几行:
When one of the task factory methods is called from within a thread pool worker thread, the default task scheduler places the new task in that thread’s local task queue. This is a faster operation than placing it in the global queue.
根据我从上一段中推断出的内容,我编写了以下代码,认为所有任务都将由同一个工作线程执行,因为它在书中进一步写道:
any time you create a task from within another task or from within a thread pool work item, you are performing an operation that is part of some larger computation
Task.Factory.StartNew(() =>
{
Thread.Sleep(1000);
Console.WriteLine("Task Id for A task: {0}", Thread.CurrentThread.ManagedThreadId);
// subtasks within Global Task
var t2 = Task.Factory.StartNew(() => { Thread.Sleep(500); Console.WriteLine("Task Id for B task : {0}", Thread.CurrentThread.ManagedThreadId); });
var t3 = Task.Factory.StartNew(() => { Thread.Sleep(1000); Console.WriteLine("Task Id for C task: {0}", Thread.CurrentThread.ManagedThreadId); });
var t4 = Task.Factory.StartNew(() => { Thread.Sleep(2000); Console.WriteLine("Task Id for D task: {0}", Thread.CurrentThread.ManagedThreadId); });
Task.WaitAll(t2, t3, t4);
});
但是出乎我的意料,结果竟然是:
结果:
任务的任务 ID:1
B 任务的任务 ID:2
D 任务的任务 ID:4
C 任务的任务 ID:3
期望:
任务的任务 ID:1
B 任务的任务 ID:1
D 任务的任务 ID:1
C 任务的任务 ID:1
看来我的直觉误导了我!我在哪里丢失了曲目?
您忘记了窃取工作,它很可能与您的第一个报价位于同一部分。如果您删除 sleeps 和 WaitAll,您会得到什么结果。还有 task Id != thread Id 你正在检查错误的值以查看线程共享。