Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo

1

Visual Studio 2010Using the Parallel Computing PlatformPhil Penningtonphilpenn@microsoft.com

2

Agenda2What’s new with Windows?Parallel Computing Tools in Visual StudioUsing .NET Parallel Extensions

3

First, An ExampleMonte Carlo Approximation of PiS = 4*r*r C = Pi*r*rPi = 4*(C/S)For each Point (P),d(P) = SQRT((x * x) + (y * y))if (d < r) thenP(x,y) is in C

4

Windows and Maximum ProcessorsBefore Win7/R2, the maximum number of Logical Processors (LPs) was dictated by processor integral word sizeLP state (e.g. idle, affinity) represented in word-sized bitmask32-bit Windows: 32 LPs64-bit Windows: 64 LPs32-bit Idle Processor Mask31016BusyIdle

5

Processor GroupsNew with Windows7 and Windows Server R25GROUPNUMA NODESocketSocketCoreCoreLPLPLPLPCoreCoreNUMA NODE

6

Processor GroupsExample: 2 Groups, 4 nodes, 8 sockets, 32 cores, 128 LP’s 6GroupGroupNUMA NodeNUMA NodeSocketSocketSocketSocketNUMA NodeNUMA NodeSocketSocketSocketSocketCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLP

7

Many-Core Topology APIs Discovery7

8

Many-Core Topology APIs Resource Localization8

9

Many-Core Topology APIs Memory Management9

10

User Mode SchedulingArchitectural PerspectiveUMS Scheduler’s Ready ListYour SchedulerLogicWaitReason:YieldReason:YieldReason:BlockedReason:CreatedCPU 1CPU 2UMS Completion ListW1W2W3W4S1S2ApplicationKernelBlocked Worker ThreadsScheduler Threads

11

Task Scheduling with a UMS SchedulerMaximize Quantum, Minimize Blocking AffectsTasks are run by worker threads, which the scheduler controlsDead ZoneWT0WT1WT2WT3Without UMS (signal-and-wait)WT0WT1WT2WT3With UMS (UMS yield)

12

Load-Balancing, Work Stealing SchedulerDynamicSchedulingStatic SchedulingCPU0CPU1CPU2CPU3CPU0CPU1CPU2CPU3Dynamic scheduling improves performance by distributing work efficiently at runtime.

13

DemosThe Platform- Topology- Schedulers

14

Agenda14What’s new with Windows?Parallel Computing Tools in Visual StudioUsing .NET Parallel Extensions

15

Visual Studio 2010, .NET Developer Tools, Programming Models, RuntimesToolsProgramming Models – Structured ParallelismParallel LINQ(PLINQ)Task ParallelLibrary (TPL)Debugger Data Structures.NET Parallel ExtensionsProfilerTask SchedulerResource Manager.NET RuntimeThreads PoolsManaged LibraryTools

16

Thread-Pool Scheduler in .NET 4.0Thread 1Dispatch LoopThread 2Dispatch LoopThread NDispatch LoopEnqueueDequeueT1T2T3T4Global Queue (FIFO)DequeueEnqueueT5Global Q is shared by legacy ThreadPool API and TPLLocal work queues and work stealing scheduler (TPL only)T6T7T8StealStealStealThread 1Local Queue (LIFO)Thread 2Local Queue (LIFO)Thread NLocal Queue (LIFO)

17

Task Parallel Library (TPL)Tasks ConceptsCommon Functionality: waiting, cancellation, continuations, parent/child relationships

18

Primitives and StructuresThread-safe, scalable collectionsIProducerConsumerCollection<T>ConcurrentQueue<T>ConcurrentStack<T>ConcurrentBag<T>ConcurrentDictionary<TKey,TValue>Phases and work exchangeBarrier BlockingCollection<T>CountdownEventPartitioning{Orderable}Partitioner<T>Partitioner.CreateException handlingAggregateExceptionInitializationLazy<T>LazyInitializer.EnsureInitialized<T>ThreadLocal<T>LocksManualResetEventSlimSemaphoreSlimSpinLockSpinWaitCancellationCancellationToken{Source}

19

Parallel DebuggingTwo new debugger toolwindowsSupport both native and managed“Parallel Tasks”“Parallel Stacks”

20

Parallel TasksWhat threads are executing my tasks?

21

Where are my tasks running (location, call stack)?

22

Which tasks are blocked?

23

How many tasks are waiting to run?Parallel StacksZoom controlMultiple call stacks in a single view

24

Task-specific view (Task status)

25

Easy navigation to any executing method

26

Rich UI (zooming, panning, bird’s eye view, flagging, tooltips)Bird’s eye view

27

Parallel Profiling

28

CPU UtilizationOther processesNumber of coresIdle timeYour Process

29

ThreadsMeasure time for interesting segmentsHide uninteresting threadsZoom in and outDetailed thread analysis(one channel per thread)Active LegendUsage HintsCall Stacks

30

CoresEach logical core in a swim laneOne color per threadMigration visualizationCross-core migration details

31

DemoLibrariesLanguagesDebuggersProfilers

32

Agenda27What’s new with Windows?Parallel Computing Tools in Visual StudioUsing .NET Parallel Extensions

33

Thinking Parallel - “Task” vs. “Data” ParallelismTask ParallelismParallel.Invoke(		() =>	{ Console.WriteLine("Begin first task...");  },        	() =>	{ Console.WriteLine("Begin second task..."); }, 		() =>	{ Console.WriteLine("Begin third task...");  } ); Data ParallelismIEnumerable<int> numbers = Enumerable.Range(2, 100-3);varmyQuery = 		from n in numbers.AsParallel()		where Enumerable.Range(2, (int)Math.Sqrt(n)).All(i => n % i > 0)		select n;int[] primes = myQuery.ToArray();

More Related Content

Using Parallel Computing Platform - NHDNUG

  • 1. Visual Studio 2010Using the Parallel Computing PlatformPhil Penningtonphilpenn@microsoft.com
  • 2. Agenda2What’s new with Windows?Parallel Computing Tools in Visual StudioUsing .NET Parallel Extensions
  • 3. First, An ExampleMonte Carlo Approximation of PiS = 4*r*r C = Pi*r*rPi = 4*(C/S)For each Point (P),d(P) = SQRT((x * x) + (y * y))if (d < r) thenP(x,y) is in C
  • 4. Windows and Maximum ProcessorsBefore Win7/R2, the maximum number of Logical Processors (LPs) was dictated by processor integral word sizeLP state (e.g. idle, affinity) represented in word-sized bitmask32-bit Windows: 32 LPs64-bit Windows: 64 LPs32-bit Idle Processor Mask31016BusyIdle
  • 5. Processor GroupsNew with Windows7 and Windows Server R25GROUPNUMA NODESocketSocketCoreCoreLPLPLPLPCoreCoreNUMA NODE
  • 6. Processor GroupsExample: 2 Groups, 4 nodes, 8 sockets, 32 cores, 128 LP’s 6GroupGroupNUMA NodeNUMA NodeSocketSocketSocketSocketNUMA NodeNUMA NodeSocketSocketSocketSocketCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreCoreLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLPLP
  • 8. Many-Core Topology APIs Resource Localization8
  • 9. Many-Core Topology APIs Memory Management9
  • 10. User Mode SchedulingArchitectural PerspectiveUMS Scheduler’s Ready ListYour SchedulerLogicWaitReason:YieldReason:YieldReason:BlockedReason:CreatedCPU 1CPU 2UMS Completion ListW1W2W3W4S1S2ApplicationKernelBlocked Worker ThreadsScheduler Threads
  • 11. Task Scheduling with a UMS SchedulerMaximize Quantum, Minimize Blocking AffectsTasks are run by worker threads, which the scheduler controlsDead ZoneWT0WT1WT2WT3Without UMS (signal-and-wait)WT0WT1WT2WT3With UMS (UMS yield)
  • 12. Load-Balancing, Work Stealing SchedulerDynamicSchedulingStatic SchedulingCPU0CPU1CPU2CPU3CPU0CPU1CPU2CPU3Dynamic scheduling improves performance by distributing work efficiently at runtime.
  • 14. Agenda14What’s new with Windows?Parallel Computing Tools in Visual StudioUsing .NET Parallel Extensions
  • 15. Visual Studio 2010, .NET Developer Tools, Programming Models, RuntimesToolsProgramming Models – Structured ParallelismParallel LINQ(PLINQ)Task ParallelLibrary (TPL)Debugger Data Structures.NET Parallel ExtensionsProfilerTask SchedulerResource Manager.NET RuntimeThreads PoolsManaged LibraryTools
  • 16. Thread-Pool Scheduler in .NET 4.0Thread 1Dispatch LoopThread 2Dispatch LoopThread NDispatch LoopEnqueueDequeueT1T2T3T4Global Queue (FIFO)DequeueEnqueueT5Global Q is shared by legacy ThreadPool API and TPLLocal work queues and work stealing scheduler (TPL only)T6T7T8StealStealStealThread 1Local Queue (LIFO)Thread 2Local Queue (LIFO)Thread NLocal Queue (LIFO)
  • 17. Task Parallel Library (TPL)Tasks ConceptsCommon Functionality: waiting, cancellation, continuations, parent/child relationships
  • 18. Primitives and StructuresThread-safe, scalable collectionsIProducerConsumerCollection<T>ConcurrentQueue<T>ConcurrentStack<T>ConcurrentBag<T>ConcurrentDictionary<TKey,TValue>Phases and work exchangeBarrier BlockingCollection<T>CountdownEventPartitioning{Orderable}Partitioner<T>Partitioner.CreateException handlingAggregateExceptionInitializationLazy<T>LazyInitializer.EnsureInitialized<T>ThreadLocal<T>LocksManualResetEventSlimSemaphoreSlimSpinLockSpinWaitCancellationCancellationToken{Source}
  • 19. Parallel DebuggingTwo new debugger toolwindowsSupport both native and managed“Parallel Tasks”“Parallel Stacks”
  • 20. Parallel TasksWhat threads are executing my tasks?
  • 21. Where are my tasks running (location, call stack)?
  • 22. Which tasks are blocked?
  • 23. How many tasks are waiting to run?Parallel StacksZoom controlMultiple call stacks in a single view
  • 25. Easy navigation to any executing method
  • 26. Rich UI (zooming, panning, bird’s eye view, flagging, tooltips)Bird’s eye view
  • 28. CPU UtilizationOther processesNumber of coresIdle timeYour Process
  • 29. ThreadsMeasure time for interesting segmentsHide uninteresting threadsZoom in and outDetailed thread analysis(one channel per thread)Active LegendUsage HintsCall Stacks
  • 30. CoresEach logical core in a swim laneOne color per threadMigration visualizationCross-core migration details
  • 32. Agenda27What’s new with Windows?Parallel Computing Tools in Visual StudioUsing .NET Parallel Extensions
  • 33. Thinking Parallel - “Task” vs. “Data” ParallelismTask ParallelismParallel.Invoke( () => { Console.WriteLine("Begin first task..."); }, () => { Console.WriteLine("Begin second task..."); }, () => { Console.WriteLine("Begin third task..."); } ); Data ParallelismIEnumerable<int> numbers = Enumerable.Range(2, 100-3);varmyQuery = from n in numbers.AsParallel() where Enumerable.Range(2, (int)Math.Sqrt(n)).All(i => n % i > 0) select n;int[] primes = myQuery.ToArray();
  • 34. Thinking Parallel – How to Partition Work? Several partitioning schemes built-inChunkWorks with any IEnumerable<T>Single enumerator shared; chunks handed out on-demandRangeWorks only with IList<T>Input divided into contiguous regions, one per partitionStripeWorks only with IList<T>Elements handed out round-robin to each partitionHashWorks with any IEnumerable<T>Elements assigned to partition based on hash codeCustom partitioning available through Partitioner<T>Partitioner.Create available for tighter control over built-in partitioning schemes
  • 35. Thinking Parallel – How to Execute Tasks?
  • 36. Thinking Parallel – How to Collate Results?
  • 38. ResourcesNativeAPIs/runtimes (Visual C++ 10)Tasks, loops, collections, and Agentshttp://msdn.microsoft.com/en-us/library/dd504870(VS.100).aspxTools (in the VS2010 IDE)Debugger and profilerhttp://msdn.microsoft.com/en-us/library/dd460685(VS.100).aspxManaged APIs/runtimes (.NET 4)Tasks, loops, collections, and PLINQhttp://msdn.microsoft.com/en-us/library/dd460693(VS.100).aspxGeneral VS2010 Parallel Computing Developer Centerhttp://msdn.microsoft.com/en-us/concurrency/default.aspx

Editor's Notes

  1. Let’s use this slide for an “Architectural Perspective” of UMS.&lt;CLICK&gt;S1 and S2 are the first threads created within a UMS solution. These are “Scheduler Threads” or “Primary Threads”. These threads represent “core” or physical CPU’s from a Scheduler perspective. These are normal threads to begin with, but you would typically first establish processor affinity using the new CreateRemoteThreadEx API and the use a new API, EnterUmsSchedulingMode, to specify that the new thread is a Scheduler thread.You pass in a callback, i.e. UMSSchedulerProc, function pointer to begin executing instructions on the Scheduler thread.A UMS worker thread is created by calling CreateRemoteThreadEx with the PROC_THREAD_ATTRIBUTE_UMS_THREAD attribute and specifying a UMS thread context and a completion list. The OS places these threads into the Completion List and your Scheduler logic takes over typically placing the new threads onto the Scheduler’s Ready List.&lt;CLICK&gt;The first thing that a Scheduler should do is move it’s associated Worker threads onto the Scheduler’s Ready List. Then, it can began executing your customer scheduler logic.&lt;CLICK&gt;Each of the Scheduler threads should then pop a Worker thread off of the Ready List and run it on the associated Core. When this occurs, the Scheduler thread context is essentially lost forever… the Worker thread now owns the core and is executing. The Scheduler thread will not regain the core until a processor Yield event occurs.&lt;CLICK&gt;The first thing that could happen is that this thread could yield. Yield is again a Scheduler callback mechanism and perhaps the single most important function of UMS. It’s within the Yield that you will implement your own synchronization primitives and scheduling logic.Ideally, the yielding thread provides some contextual information to the scheduler (maybe it wants to wait on some specific application domain event to occur). Your Scheduler would look at this Yield request and associated context and make a scheduling decision.&lt;CLICK&gt;Maybe the Scheduler places the Worker thread within a Wait list for that specific event or event type.Now your Scheduler has to decide what to run next. &lt;CLICK&gt;Maybe the next Worker thread from the Ready List, for instance… and we’re back running again. Note, that no kernel scheduling context switch was necessary. Maybe that wait event handling took 200 cycles in user-mode. It may have cost 10 times that with a kernel context switch.&lt;CLICK&gt;Let’s now assume that this worker performs a system call… At this point, we switch the worker thread to it’s kernel-mode context and the thread continues to run within the kernel. If it does not block (in other words, if it doesn’t use one of the kernel synchronization primitives, then it just continues to run. If the thread never blocks in the kernel, then it just returns to user-mode and continues to run and do work.&lt;CLICK&gt;Let’s assume that the thread does block. Maybe a page fault occurred, for instance. Now our Scheduler thread regains control of the processor via a callback from the kernel. Now, the kernel is telling your Scheduler that a worker thread is blocked and the reason for that block. This is the point where we integrate kernel synchronization with user synchronization. But now, you get to decide what to run next.&lt;CLICK&gt;The Scheduler looks at the state of it’s affairs and perhaps decides to run the next Worker thread from the Ready List, for example.Let’s assume that later in time Worker 3 unblocks. &lt;CLICK&gt;The kernel will now place this unblocked Worker thread into the UMS Completion List.&lt;CLICK&gt;At the next Yield event, for instance, we get another Scheduler decision opportunity. Maybe this Yield contains information that affects the state of our Wait list.&lt;CLICK&gt;The first thing that the Scheduler should do, however, is manage the Completion List and move any unblocked threads to the Ready List.&lt;CLICK&gt;Next, our Scheduler must make a priority decision. Maybe our Waiting thread gets to run again and our Yielding thread gets placed upon the Ready List.And we’re done…
  2. UMS is an enabler for:Finer-grained parallelismMore deterministic behaviorBetter cache localityUMS allows your Scheduler to boost performance in certain situations:Apps that have a lot of blocking, for example
  3. Think Tasks not Threads.Threads represent execution flow, not workHard-coded; significant system overheadMinimal intrinsic parallel constructsQueueUserWorkItem() is handy for fire-and-forgetBut what about…WaitingCancelingContinuingComposingExceptionsDataflowIntegrationDebugging
  4. NOW, LET’S FIRST CONSIDER THE TOOLS ARCHICTECTURE FROM A .NET DEVELOPER’S PERSPECTIVE.LET’S START WITH THE .NET Runtime AND THE .NET Parallel Extensions library. In a moment, we’ll look at how a developer uses the extensions within their application. The .NET PARALLEL EXTENSIONS provide the benefits of concurrent task scheduling without YOU having to build a custom scheduler that is appropriately reentrant, thread-safe, and non-blocking.&lt;CLICK&gt;The Parallel Extensions library contains a Task Scheduler and a Resource Manager component that integrates with the underlying .NET Runtime. The Resource Manager manages access to system resources like the collection of available CPU’s. &lt;CLICK&gt;The Scheduler leverages only thread pools for task scheduling. &lt;CLICK&gt;The Parallel Extensions also supports multiple Programming Models. &lt;CLICK&gt;The Task Parallel Library (TPL) is an easy and convenient way to express fine-grain parallelism within your applications. The TPL provides patterns for Task Execution, Synchronization, and Data Sharing.&lt;CLICK&gt;The PLINQ (or Parallel LINQ) enables parallel query execution not only on SQL Data but also on XML or Collections Data.&lt;CLICK&gt;The Parallel Extensions also includes Data Structures that are “scheduler aware” enabling you to optimally specify task scheduling requests and custom scheduler policies.&lt;CLICK&gt;Again, Visual Studio 2010 includes new tools for parallel application development and testing. These include:&lt;CLICK&gt;A new parallel debugger. And…&lt;CLICK&gt;A new parallel application profiler.Let’s take a brief look at a simple .NET parallel application along with the Visual Studio 2010 Debugger and Parallel Performance Analyzer.Pure .NET librariesFeature areasTask Parallel LibraryParallel LINQSynchronization primitives and thread-safe data structuresEnhanced ThreadPool