View
576
Download
2
Category
Preview:
DESCRIPTION
TPL(Task Parallel Library)에 대한 소개입니다. 데모 코드 - Multi Threading https://github.com/gyuwon/DotNetPractice/blob/master/Tasks/MultiThreading/Program.cs - Shard Resource Access https://github.com/gyuwon/DotNetPractice/blob/master/Tasks/SharedResourceAccess/Program.cs - Continuation https://github.com/gyuwon/DotNetPractice/blob/master/Tasks/Chapters/Program.cs - Parallelism Performance https://github.com/gyuwon/DotNetPractice/blob/master/Tasks/ParallelismPerformance/Program.cs - foreach vs. ForAll https://github.com/gyuwon/DotNetPractice/blob/master/Tasks/ForAll/Program.cs
Citation preview
TPL(Task Parallel Library)
이규원 (gyuwon@live.com)
http://justhackem.wordpress.com
https://www.facebook.com/gyuwon.yi
Background
Thread
• 운영체제가 프로세서 자원 (CPU Time) 을 할당하는 기본 단위• Multi Threading
• Parallel Processing• UI & Background Tasks• Shared Resource Access
DEMO
Multi Threading
Shared Resource Access
Thread Pool
• 큐에 입력되는 작업들을 작업자 스레드에 할당해 처리• Recycling
Thread PoolThread
Thread
Thread
…Work Item Queue
Future
• 아직 결정 여부가 확실하지 않은 값에 대한 계산 작업 및 노출• Future 가 생성될 때 값은 결정되어 있거나 결정되어 있지 않음• 값이 반환되는 시점에는 값이 결정되어 있음• Promise
Tasks
Task
• Task ≠ Thread
• Task is a ‘Work Item’ (IThreadPoolWorkItem)
• Future
• Awaitable
• Task Scheduler
Default Task Scheduler
Thread Pool
Worker Thread
Local Queue
Worker Thread
Local Queue
Global Queue
Task
TaskTask Task
Task
TaskTask Task
…
…
… …
LIFO LIFO
FIFOWork Stealing
Start
protected internal override void QueueTask(Task task) { if ((task.Options & TaskCreationOptions.LongRunning) != 0) {
Thread thread = new Thread(…); thread.IsBackground = true; thread.Start(task); } else { …
ThreadPool.UnsafeQueueCustomWorkItem(task, …); } }
FromAsync
internal static Task FromAsyncImpl(IAsyncResult asyncResult, …) { … Task t = new Task(…); if (asyncResult.IsCompleted) {
t.InternalRunSynchronously(…); } else {
ThreadPool.RegisterWaitForSingleObject(…); } …}
Result
• TResult Task<TResult>.Result
• 작업이 완료된 상태이면 즉시 반환• 작업이 완료되지 않은 상태이면 완료될 때까지 대기
Continuation
• Task 완료 후 실행 할 Task 를 생성• ContinueWith
• GetAwaiter
ContinueWith
internal void ContinueWithCore(Task continuationTask, ...){ … if (!continuationTask.IsCompleted) { … // Attempt to enqueue the continuation
bool continuationQueued = AddTaskContinuation(…); // If the continuation was not queued (because the task completed), then run it now.
if (!continuationQueued) continuation.Run(this, …); }}
DEMO
Continuation
PLINQ(Parallel Linq)
Data Parallelism
Sequential Parallel
Proces-sor
Proces-sor
Proces-sor
…Proces-
sor
Parallel Query
Queryfrom e in querywhere …select …
Parallel Query
from e in query.AsParallel()where …select …
DEMO
Performance
foreach vs. ForAll
foreach ForAll
Proc A
Proc A
Proc A
…Proc B
Proc A
Proc A
Proc A
…
Proc B
Proc B
Proc B
…
DEMO
foreach vs. ForAll
Recommended