Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Migration To Multi Core - Parallel Programming Models


Published on

This is a 1-day parallel programming workshop, I gave more than a year ago.

Published in: Technology

Migration To Multi Core - Parallel Programming Models

  1. 1. Migration to Multi-Core Zvi Avraham, CTO [email_address]
  2. 2. Agenda <ul><li>Muli-Core and Many-Core </li></ul><ul><li>Hardware slides (another PowerPoint) </li></ul><ul><li>Parallel Programming Models </li></ul><ul><li>CPU Affinity </li></ul><ul><li>Parallel Programming APIs </li></ul><ul><li>Win32 Threads API </li></ul><ul><li>OpenMP Tutorial (another PowerPoint) </li></ul><ul><li>Intel TBB – Thread Building Blocks (if time permits) </li></ul><ul><li>Demos – C++ source code samples </li></ul><ul><li>Summary </li></ul><ul><li>Questions </li></ul>
  3. 3. Multi-Core vs. Many-Core Multi-Core: ≤8 cores/threads Many-Core: >8 cores/threads
  4. 4. Multi-Core x86 <ul><li>AMD Athlon X2 </li></ul><ul><li>AMD Opteron Dual-Core </li></ul><ul><li>AMD Barcelona Quad-Core </li></ul><ul><li>AMD Phenom Triple-Core </li></ul><ul><li>Pentium D </li></ul><ul><li>Intel Core 2 Duo </li></ul><ul><li>Intel Core 2 Quad </li></ul><ul><li>Dual Core Xeon </li></ul><ul><li>Quad Core Xeon </li></ul>
  5. 5. Many-Core Processors (MPU) the replacement for DSP and FPGA <ul><li>Sun UltraSPARC T2 / Niagara – 8 cores x 8 threads </li></ul><ul><ul><li>(fastest commodity processor for today) </li></ul></ul><ul><li>Sun UltraSPARC RK / Rock – 16 cores x 2 threads </li></ul><ul><li>RMI XLR™ 732 Processor – 8 cores x 4 threads (MIPS) </li></ul><ul><li>Cavium OCTEON – 16 cores (MIPS) </li></ul><ul><li>TILERA TILE64 – 64 cores (MIPS) </li></ul>
  6. 6. Intel Tera-scale <ul><li>80 cores ~ 1.81 Teraflops, 2 GB RAM on chip </li></ul><ul><li>Currently only prototype (expected in 2009/2010) </li></ul>
  7. 7. Cell Processor SONY Playstation 3 <ul><li>1 main PowerPC core x 2 threads @ 3 GHz </li></ul><ul><li>+ 7 “Synregistic Processing Elements” @ 3 GHz </li></ul><ul><li>Total – 9 threads </li></ul>
  8. 8. Xenon CPU Microsoft XBOX 360 <ul><li>PowerPC – 3 Cores x 2 Threads @ 3.2 GHz </li></ul>
  9. 9. NVIDIA GeForce 8800GTX <ul><li>128 Stream Processors @ 1.3 Ghz, ~520GFlops </li></ul>
  10. 10. Intel Larrabee GPU <ul><li>Up to 48 cores x 4 threads </li></ul><ul><li>Cores based on Pentium (x86-64) </li></ul><ul><li>512 bit SIMD </li></ul>
  11. 11. Hardware Slides <ul><li>See external PowerPoint presentation: </li></ul><ul><ul><li>Maximizing Desktop Application Performance on Dual-Core PC Platforms </li></ul></ul>
  12. 12. Parallel Programming Models
  13. 13. Concurrent/Parallel/Distributed <ul><li>Concurrency </li></ul><ul><ul><li>property of systems in which several computational processes are executing at the same time, and potentially interacting with each other </li></ul></ul><ul><li>Parallel </li></ul><ul><ul><li>computation in which many calculations are carried out simultaneously, operating on the principle that large problems can often be divided into smaller ones, which are then solved concurrently (&quot;in parallel&quot;) </li></ul></ul><ul><li>Distributed </li></ul><ul><ul><li>The tasks running on different interconnected computers </li></ul></ul>
  14. 14. Levels of HW Parallelism <ul><li>Bit-level </li></ul><ul><ul><li>(i.e. from 8bit to 16bit to 32bit to 64bit CPUs) </li></ul></ul><ul><li>Instruction-level </li></ul><ul><ul><li>(CPU scheduling multiple instruction simultaneously) </li></ul></ul><ul><ul><li>SIMD </li></ul></ul><ul><li>SMT – Simultaneous Multi-Threading </li></ul><ul><li>CMP – Core Multi-Processing </li></ul><ul><li>SMP – Symmetric Multi-Processing </li></ul><ul><li>Cluster – computers with fast interconnect </li></ul><ul><li>Grid – network of loosely connected computers </li></ul>
  15. 15. Flynn’s Taxonomy Single Instruction Multiple Instruction Single Data SISD MISD Multiple Data SIMD MIMD
  16. 16. Flynn’s Taxonomy (2)
  17. 17. Parallel Programming Models <ul><li>How can we write programs that run faster on a multi-core CPU? </li></ul><ul><li>How can we write programs that do not crash on a multi-core CPU? </li></ul><ul><li>Choose the right model! </li></ul><ul><li>There are two fundamental parallel programming models: </li></ul><ul><ul><li>Shared State (Shared Memory) </li></ul></ul><ul><ul><li>Message Passing (Distributed Memory) </li></ul></ul><ul><li>DSM (Distributed Shared Memory) – academic </li></ul>
  18. 18. Shared State <ul><li>Shared state concurrency involves the idea of “mutable state” (literally memory that can be changed). </li></ul><ul><li>This is fine as long as you have only one process/thread doing the changing. </li></ul><ul><li>If you have multiple processes sharing and modifying the same memory, you have a recipe for disaster - madness lies here. </li></ul><ul><li>To protect against the simultaneous modification of shared memory, we use a locking mechanism. Call this a mutex, critical section, synchronized method, or whatever you like, but it’s still a lock. </li></ul>
  19. 19. Message Passing <ul><li>In message passing concurrency, there is no shared state. All computations are done inside processes/threads, and the only way to exchange data is through asynchronous message passing. </li></ul><ul><li>Why this is good? </li></ul><ul><ul><li>No need in locks. </li></ul></ul><ul><ul><li>No locks – no deadlocks (almost) </li></ul></ul><ul><ul><li>No locks – deterministic execution – good for Real Time. </li></ul></ul><ul><ul><li>No locks – good for I/O-bounded applications – Efficient Network Programming. </li></ul></ul>
  20. 20. Message Passing (cont.) <ul><li>ActiveObject design pattern </li></ul><ul><ul><li>ActiveObject is an Object with it’s own thread of control and attached message queue. </li></ul></ul><ul><ul><li>On arrival of message, ActiveObject wakes up and execute the command in the message. </li></ul></ul><ul><ul><li>Optionally, sends the result back to caller (via callback or Future). </li></ul></ul><ul><li>Rational Rose Capsule design pattern </li></ul><ul><ul><li>The same as ActiveObject, but with attached FSM. </li></ul></ul><ul><ul><li>Messages called “Events”. </li></ul></ul><ul><ul><li>Events changing FSM State according to state transition table. </li></ul></ul><ul><li>MPI (Message Passing Interface) - de-facto standard API for Message Passing between nodes in the computational clusters. </li></ul>
  21. 21. Active Object Design Pattern
  22. 22. Rational’s Capsule ROOM – Real-Time Object Oriented Modeling
  23. 23. Implicit vs. Explicit Parallelism <ul><li>Implicit Parallelism </li></ul><ul><ul><li>Automatic parallelization of code by compiler or library </li></ul></ul><ul><ul><li>A pure implicitly parallel language does not need special directives, operators or functions to enable parallel execution. </li></ul></ul><ul><ul><li>Programmer focused on core tasks, instead of worry about division on tasks and communication </li></ul></ul><ul><ul><li>Less degree of control by programmer </li></ul></ul><ul><ul><li>Less effective </li></ul></ul><ul><ul><li>Examples: Matlab, R, LabView, NESL, ZPL, Intel Ct library for C++ </li></ul></ul>
  24. 24. Implicit vs. Explicit Parallelism <ul><li>Explicit Parallelism </li></ul><ul><ul><li>representation of concurrent computations by means of primitives in the form of special-purpose directives or function calls, also called “parallelization overhead” </li></ul></ul><ul><ul><li>Most parallel primitives are related to process synchronization, communication or task partitioning </li></ul></ul><ul><ul><li>Full control by programmer </li></ul></ul><ul><ul><li>Examples: thread APIs, Erlang, Ada, cilk, etc. </li></ul></ul>
  25. 25. Data Parallel vs. Task Parallel <ul><li>Data Parallelism </li></ul><ul><ul><li>a form of parallelization of computing across multiple processors in parallel computing environments. Data parallelism focuses on distributing the data across different parallel computing nodes. </li></ul></ul><ul><li>Task Parallelism </li></ul><ul><ul><li>a form of parallelization of computer code across multiple processors in parallel computing environments. Task parallelism focuses on distributing execution processes (threads) across different parallel computing nodes. </li></ul></ul><ul><li>Most real programs fall somewhere on a continuum between Task parallelism and Data parallelism. </li></ul>
  26. 26. Data Parallel example <ul><li>if CPU=&quot;a&quot; then </li></ul><ul><li>low_limit=1 </li></ul><ul><li>upper_limit=50 </li></ul><ul><li>else if CPU=&quot;b&quot; then </li></ul><ul><li>low_limit=51 </li></ul><ul><li>upper_limit=100 </li></ul><ul><li>end if </li></ul><ul><li>for i = low_limit to upper_limit </li></ul><ul><li>Task on d(i) </li></ul><ul><li>end for </li></ul>
  27. 27. Task Parallel example <ul><li>program: </li></ul><ul><li>... </li></ul><ul><li>if CPU=&quot;a&quot; then </li></ul><ul><li>do task &quot;A&quot; </li></ul><ul><li>else if CPU=&quot;b&quot; then </li></ul><ul><li>do task &quot;B&quot; </li></ul><ul><li>end if </li></ul><ul><li>... </li></ul><ul><li>end program </li></ul>
  28. 28. “ Plain” vs Nested Data Parallelism <ul><li>“ Plain” Data Parallelism </li></ul><ul><ul><li>Good for regular data (vectors, matrices) </li></ul></ul><ul><ul><li>No support for control flow </li></ul></ul><ul><ul><li>Efficient impl. on SIMD or GPGPU HW </li></ul></ul><ul><li>Nested Data Parallelism </li></ul><ul><ul><li>Support irregular or sparse data </li></ul></ul><ul><ul><li>Can express control flow </li></ul></ul><ul><ul><li>Efficient impl. on Multi-core CPUs with SIMD </li></ul></ul><ul><ul><li>Examples: </li></ul></ul><ul><ul><ul><li>[a:5, b:7] + [b:3, c:3, d:1] = [a:5, b:10, c:3, d:1] </li></ul></ul></ul><ul><ul><ul><li>sum( [a:5, a:3, b:2, b:4, d:1] ) = [a:8, b:6, d:1] </li></ul></ul></ul>
  29. 29. Parallel Models <ul><li>Data Parallel models: </li></ul><ul><ul><li>Work Sharing (using Fork / Join) </li></ul></ul><ul><ul><ul><li>Parallel For </li></ul></ul></ul><ul><ul><li>Scatter / Gather </li></ul></ul><ul><ul><li>Map / Reduce </li></ul></ul><ul><ul><ul><li>Split / Map / Combine / Reduce / Merge </li></ul></ul></ul><ul><li>Task Parallel models: </li></ul><ul><ul><li>Fork / Join </li></ul></ul><ul><ul><li>Recursive Fork / Join (Work Stealing scheduler) </li></ul></ul><ul><ul><li>Scheduler / Workers (aka Master / Slave) </li></ul></ul><ul><ul><ul><li>Compute Grid: Executer / Scheduler / Workers </li></ul></ul></ul>
  30. 30. Scatter / Gather
  31. 31. Fork / Join Barries – “joins” Parallel Regions Master Thread
  32. 32. Recursive Fork/Join <ul><li>Result solve (Problem problem) {               if (problem is small)                        directly solve problem             else {                     split problem into independent parts                       fork new subtasks to solve each part                       join all subtasks                       compose result from subresults              } } </li></ul>
  33. 33. Map / Reduce <ul><li>Input & Output: each a set of key/value pairs </li></ul><ul><li>Programmer specifies two functions: </li></ul><ul><ul><li>map (in_key, in_value) -> </li></ul></ul><ul><ul><li>list(out_key, intermediate_value) </li></ul></ul><ul><ul><ul><li>Processes input key/value pair </li></ul></ul></ul><ul><ul><ul><li>Produces set of intermediate pairs </li></ul></ul></ul><ul><ul><li>reduce (out_key, list(intermediate_value)) -> list(out_value) </li></ul></ul><ul><ul><ul><li>Combines all intermediate values for a particular key </li></ul></ul></ul><ul><ul><ul><li>Produces a set of merged output values (usually just one) </li></ul></ul></ul>
  34. 34. Map / Reduce
  35. 35. Types of Parallelism <ul><li>Fine-grained </li></ul><ul><ul><li>when tasks need to communicate many-times per second </li></ul></ul><ul><ul><li>small messages </li></ul></ul><ul><ul><li>low-latency </li></ul></ul><ul><li>Coarse-grained </li></ul><ul><ul><li>when tasks do not need to communicate many times per second </li></ul></ul><ul><li>Embarrassing parallelism </li></ul><ul><ul><li>tasks are independent </li></ul></ul>
  36. 36. Embarrassingly Parallel Problems <ul><li>Embarrassingly Parallel Problem is one for which no particular effort is needed to segment the problem into a very large number of parallel tasks. </li></ul><ul><li>And there is no essential dependency (or communications) between those parallel tasks. </li></ul><ul><li>If each step can be computed independently from every other step, thus each step could be made to run on a separate processor to achieve quicker results. </li></ul><ul><li>Examples: </li></ul><ul><ul><li>running the same algorithm on each grabbed frame </li></ul></ul><ul><ul><li>running the same algorithm with different parameters </li></ul></ul>
  37. 37. Extended Flynn’s Taxonomy <ul><li>SPMD - Single Program, Multiple Data streams </li></ul><ul><ul><li>Multiple autonomous processors simultaneously executing the same program (but at independent points, rather than in the lockstep that SIMD imposes) on different data. Also referred to as 'Single Process, multiple data' [6] . SPMD is the most common style of parallel programming [7] . </li></ul></ul><ul><li>MPMD - Multiple Program, Multiple Data streams </li></ul><ul><ul><li>Multiple autonomous processors simultaneously operating at least 2 independent programs. Typically such systems pick one node to be the &quot;host&quot; (&quot;the explicit host/node programming model&quot;) or &quot;manager&quot; (the &quot;Manager/Worker&quot; strategy), which runs one program that farms out data to all the other nodes which all run a second program. Those other nodes then return their results directly to the manager. </li></ul></ul>
  38. 38. CPU Affinity Changing Process and Thread Affinity
  39. 39. CPU Affinity <ul><li>The system uses a symmetric multiprocessing (SMP) model to schedule processes and threads on multiple processors. </li></ul><ul><li>Any process/thread can be assigned to any processor. </li></ul><ul><li>On a single CPU system threads can’t run concurrently, but using time-slicing model. </li></ul><ul><li>On a multiple CPU system threads can run concurrently on different processors. </li></ul><ul><li>Scheduling is still determined by thread priority. </li></ul><ul><li>However, on a multiprocessor computer, you can also affect scheduling by setting thread affinity and thread ideal processor (i.e. “bounding” thread to specific CPU). </li></ul>
  40. 40. Why mess with CPU Affinity? Legacy Code Migration <ul><li>Usually Windows OS handles CPU Affinity automatically very good. So why mess with it? </li></ul><ul><li>When migrating old applications to multi-core CPU, their performance may start degrading. This happens because OS moving application’s threads and interrupt routines between cores. </li></ul><ul><li>By fixing application’s process and threads to CPU #0, application will start behave the same way, as on uniprocessor machine. </li></ul>
  41. 41. Why mess with CPU Affinity? Real-Time and Determinism <ul><li>By setting CPU affinity for our application’s thread - we get deterministic execution times, needed for Real-Time. </li></ul><ul><li>OS will no more move our threads between cores. </li></ul><ul><li>For example, let’s say we developing video surveillance system using dual-core CPU. </li></ul><ul><li>We have two threads: </li></ul><ul><ul><li>#1 – receiving video frames from the Matrox Frame Grabber </li></ul></ul><ul><ul><li>#2 – transmitting the received frames via TCP/IP to the Server </li></ul></ul><ul><li>By setting affinity of the receiving thread on CPU #0 and of the transmitting thread on CPU #1 – we getting deterministic execution times. </li></ul>
  42. 42. Why mess with CPU Affinity? Memory Affinity <ul><li>Cache locality </li></ul><ul><ul><li>There are some multi-core CPUs with separate L1 caches (for example: Pentium-D, some Intel’s quad-core CPUs). </li></ul></ul><ul><ul><li>If OS moving thread from one core to another, the data is missing on the 2 nd core, so it must fetch data from RAM, thus we get performance degradation. </li></ul></ul><ul><li>NUMA </li></ul><ul><ul><li>On the NUMA, each memory bank connect directly to single CPU. When accessing RAM from another CPU it will be slower. </li></ul></ul><ul><ul><li>By setting thread’s CPU affinity and allocating memory on the faster RAM bank, we getting performance improvement. </li></ul></ul>
  43. 43. Changing CPU Affinity <ul><li>Using Task Manager – manualy, need to change each time, when running program </li></ul><ul><li>ImageCfg.exe Utility – modify program’s EXE image – need to do it only once </li></ul><ul><li>Process.exe Utility – change program’s affinity, without modifying it’s EXE image </li></ul><ul><li>IntFiltr.exe – Interrupt Affinity Filter tool </li></ul><ul><li>Win32 Affinity API: </li></ul><ul><ul><li>SetProcessAffinityMask </li></ul></ul><ul><ul><li>SetThreadAffinityMask </li></ul></ul>
  44. 44. CPU Affinity – Task Manager
  45. 45. CPU Affinity – Task Manager
  46. 46. ImageCFG – Affinity Mask Tool <ul><li>Change CPU Affinity mask for existing EXE file </li></ul><ul><li>WARNING: modifies .EXE file – so backup before you do anything </li></ul><ul><li>“ -u” - Marks image as uniprocessor only: </li></ul><ul><ul><li>imagecfg -u c:path ofile.exe </li></ul></ul><ul><li>“ -a” – Process Affinity mask value in hex: </li></ul><ul><ul><li>Permanently set CPU Affinity mask to CPU #1 </li></ul></ul><ul><ul><li>imagecfg -a 0x1 c:path ofile.exe </li></ul></ul><ul><ul><li>Permanently set CPU Affinity mask to CPU #2 </li></ul></ul><ul><ul><li>imagecfg -a 0x2 c:path ofile.exe </li></ul></ul>
  47. 47. Process.exe – Get Affinity Mask <ul><li>“ -a” option is used in conjunction with a process name or PID, the utility will show the System Affinity Mask and the Process Affinity Mask. </li></ul>
  48. 48. Process.exe – Set Affinity Mask <ul><li>To set the affinity mask, simply append the binary mask after the PID/Image Name. Any leading zeros are ignored, so there is no requirement to enter the full 32 bit mask. </li></ul><ul><li>Doesn’t modify EXE file – so need to run each time </li></ul>
  49. 49. IntFiltr.exe – Interrupt Affinity Filter <ul><li>Binding of device interrupts to particular processors on multiprocessor computers is a useful technique to maximize performance, scaling, and partitioning of large computers. </li></ul><ul><li>Interrupt-Affinity Filter (IntFiltr) is an interrupt-binding tool that permits you to establish affinity for device processors on multiprocessor computers. </li></ul><ul><li>IntFiltr uses Plug and Play features of Windows 2000 and provides a Graphical User Interface (GUI) to permit interrupt binding. </li></ul>
  50. 50. Parallel Programming APIs
  51. 51. Parallel Programming APIs <ul><li>Threads – native OS threads API (Win32 Threads, POSIX pthreads, etc.). Low-level, highly error-prone API. Locking, etc. </li></ul><ul><li>OpenMP – SMP standard, which allow incremental parallelization of serial code, by adding compiler directives, called “pragmas”. </li></ul><ul><li>Intel TBB – Thread Building Blocks C++ library from Intel. High-level constructs: think in terms of tasks instead of threads (like “Parallel STL”). </li></ul><ul><li>Auto-Parallelization </li></ul>
  52. 52. Simplicity / Complexity <ul><li>The native threads programming model introduces much more complexity within the code than OpenMP or Intel® TBB, making it more challenging to maintain. </li></ul><ul><li>One of the benefits of using Intel® TBB or OpenMP when appropriate is that these APIs create and manage the thread pool for you: thread synchronization and scheduling are handled automatically . </li></ul>
  53. 53. Capabilities Comparison Intel TBB OpenMP Threads Task level parallelism + + - Data decomposition support + + - Complex parallel patterns (non-loops) + - - Generic parallel patterns + - - Scalable nested parallelism support + - - Built-in load balancing + + - Affinity support - + + Static scheduling - + - Concurrent data structures + - - Scalable memory allocator + - - I/O dominated tasks - - + User-level synch. primitives + + - Compiler support is not required + - + Cross OS support + + -
  54. 54. Native Threads <ul><li>Win32 threads – CreateThread </li></ul><ul><li>POSIX threads </li></ul><ul><li>boost::threads – platform independent </li></ul><ul><li>ACE threads – platform independent, optimized for Concurrent and Network programming (used by many defense and telecom companies: Boeng, Raytheon, Elbit, Ericsson, Motorola, Lucent, Siemens, etc.) </li></ul>
  55. 55. Win32 Threads API It’s assumed, that reader/listener is familiar with basic multithreading and corresponding Win32 API
  56. 56. What are Win32 Threads? <ul><li>Microsoft Windows implementation </li></ul><ul><li>C language interface to library </li></ul><ul><ul><li>Follows Win32 programming model </li></ul></ul><ul><li>Threads exist within single process </li></ul><ul><li>All threads are peers </li></ul><ul><ul><li>No explicit parent-child model </li></ul></ul>
  57. 57. Win32 API Hierarchy for Concurrency Windows OS Job Job Process Primary Thread Thread Process Fiber Fiber
  58. 58. Process <ul><li>Each process provides the resources needed to execute a program. A process has a </li></ul><ul><ul><li>virtual address space </li></ul></ul><ul><ul><li>executable code </li></ul></ul><ul><ul><li>open handles to system objects </li></ul></ul><ul><ul><li>security context </li></ul></ul><ul><ul><li>unique process identifier </li></ul></ul><ul><ul><li>environment variables </li></ul></ul><ul><ul><li>priority class </li></ul></ul><ul><ul><li>minimum and maximum working set sizes </li></ul></ul><ul><ul><li>at least one thread of execution. </li></ul></ul><ul><li>Each process is started with a single thread, often called the primary thread , but can create additional threads from any of its threads. </li></ul>
  59. 59. Thread <ul><li>A thread is the entity within a process that can be scheduled for execution. </li></ul><ul><li>All threads of a process share its virtual address space and system resources. </li></ul><ul><li>In addition, each thread maintains: </li></ul><ul><ul><li>exception handlers </li></ul></ul><ul><ul><li>scheduling priority </li></ul></ul><ul><ul><li>thread local storage (TLS) </li></ul></ul><ul><ul><li>unique thread identifier </li></ul></ul><ul><ul><li>set of structures the system will use to save the thread context until it is scheduled. </li></ul></ul><ul><li>The thread context includes the thread's set of machine registers, the kernel stack, a thread environment block, and a user stack in the address space of the thread's process. Threads can also have their own security context, which can be used for impersonating clients. </li></ul>
  60. 60. Job object <ul><li>A job object allows groups of processes to be managed as a unit. Job objects are namable, securable, sharable objects that control attributes of the processes associated with them. Operations performed on the job object affect all processes associated with the job object. </li></ul><ul><li>Job = Process Group </li></ul><ul><li>There is no Thread Group API in Win32 (unlike ACE C++ library or Java) </li></ul>
  61. 61. Fiber / Coroutine / Microthread <ul><li>A fiber is a unit of execution that must be manually scheduled by the application. </li></ul><ul><li>Fibers run in the context of the threads that schedule them. </li></ul><ul><li>Each thread can schedule multiple fibers. </li></ul><ul><li>Fibers do not run simultaneously, so there is no need in locking of shared data </li></ul><ul><li>In general, fibers do not provide advantages over a well-designed multithreaded application. However, using fibers can make it easier to port applications that were designed to schedule their own threads. </li></ul>
  62. 62. Win32 Threads API Example: CreateThread
  63. 63. Win32 Threads API: Critical Section
  64. 64. CCriticalSection C++ Class
  65. 65. CCriticalSection & CLock example
  66. 66. Thread Affinity <ul><li>Thread affinity forces a thread to run on a specific subset of processors. </li></ul><ul><li>Use the SetProcessAffinityMask function to specify thread affinity for all threads of the process. </li></ul><ul><li>To set the thread affinity for a single thread, use the SetThreadAffinityMask function. The thread affinity must be a subset of the process affinity. </li></ul><ul><li>You can obtain the current process affinity by calling the GetProcessAffinityMask function. </li></ul><ul><li>Setting thread affinity should generally be avoided, because it can interfere with the scheduler's ability to schedule threads effectively across processors. This can decrease the performance gains produced by parallel processing. </li></ul>
  67. 67. Thread Ideal Processor <ul><li>When you specify a thread ideal processor , the scheduler runs the thread on the specified processor when possible. </li></ul><ul><li>Use the SetThreadIdealProcessor function to specify a preferred processor for a thread. </li></ul><ul><li>This does not guarantee that the ideal processor will be chosen, but provides a useful hint to the scheduler. </li></ul>
  68. 68. Our running Example: The PI program Numerical Integration  4.0 (1+x 2 ) dx =  0 1  F(x i )  x   i = 0 N Mathematically, we know that: We can approximate the integral as a sum of rectangles: Where each rectangle has width  x and height F(x i ) at the middle of interval i. F(x) = 4.0/(1+x 2 ) 4.0 2.0 1.0 X 0.0
  69. 69. PI: Matlab N=1000000; Step = 1/N; PI = Step*sum(4./(1+(((1:N)-0.5)*Step).^2)); <ul><li>Implicit Data Parallel </li></ul><ul><li>Implemented using SIMD </li></ul><ul><li>Later version of Matlab can utilize multiple / multi-core CPUs </li></ul>
  70. 70. PI Program: an example static long num_steps = 100000; double step; void main () { int i; double x, pi, sum = 0.0; step = 1.0/(double) num_steps; for (i=1;i<= num_steps; i++){ x = (i-0.5)*step; sum = sum + 4.0/(1.0+x*x); } pi = step * sum; }
  71. 71. OpenMP PI Program : Parallel for with a reduction #include <omp.h> static long num_steps = 100000; double step; #define NUM_THREADS 2 void main () { int i; double x, pi, sum = 0.0; step = 1.0/(double) num_steps; omp_set_num_threads(NUM_THREADS); #pragma omp parallel for reduction(+:sum) private(x) for (i=1;i<= num_steps; i++){ x = (i-0.5)*step; sum = sum + 4.0/(1.0+x*x); } pi = step * sum; } OpenMP adds 2 to 4 lines of code
  72. 72. OpenMP
  73. 73. OpenMP Slides <ul><li>See external PowerPoint presentation: </li></ul><ul><ul><li>OpenMP Tutorial Part 1: The Core Elements of OpenMP </li></ul></ul>
  74. 74. OpenMP Compiler Option <ul><li>How to enable OpenMP in MSVC++ 2005 </li></ul><ul><li>Project -> Properties -> Configuration Properties -> C/C++ -> Command Line : </li></ul>
  75. 75. OpenMP Compiler Option <ul><li>How to enable OpenMP in Intel Compiler: </li></ul><ul><ul><li>/Qopenmp </li></ul></ul><ul><ul><li>/Qopenmp_report{0|1|2} </li></ul></ul>
  76. 76. Auto-Parallelization <ul><li>Intel compiler only, using compiler switch: </li></ul><ul><ul><li>/Qparallel </li></ul></ul><ul><ul><li>/Qpar_report[n] </li></ul></ul><ul><li>Automatic threading of loops without having to manually insert OpenMP directives. </li></ul><ul><li>Compiler can identify “easy” canditates for parallelization </li></ul><ul><li>Large applications are difficult to analyze </li></ul>
  77. 77. Intel® TBB Thread Building Blocks C++ Library
  78. 78. Calculate PI using TBB
  79. 79. Calculate PI in MPI
  80. 80. MPI_Reduce <ul><li>Reduces values on all processes to a single value on root process </li></ul><ul><li>Synopsis </li></ul><ul><li>MPI_Reduce ( </li></ul><ul><li>void *sendbuf, // address of send buffer </li></ul><ul><li>void *recvbuf, // address of receive buffer (only at root) </li></ul><ul><li>int count, // number of elements in send buffer (integer) </li></ul><ul><li>MPI_Datatype datatype, // data type of elements of send buffer </li></ul><ul><li>MPI_Op op, // reduce operation: sum, prod, min, max, etc. </li></ul><ul><li>int root, // root rank of root process (integer) </li></ul><ul><li>MPI_Comm comm // comm communicator (handle) </li></ul><ul><li>) </li></ul>
  81. 81. Summary <ul><li>Multi-core performance improvements do not come for free in case your application is single-threaded. </li></ul><ul><li>Except for multiple concurrent applications being run faster all together. </li></ul><ul><li>Use Thread CPU Affinity to improve your applications performance and Real-Time deterministic execution. </li></ul><ul><li>Use OpenMP to parallelize your existing serial C/C++ code – minimal investment and incremental way to threading. </li></ul><ul><li>Use Intel® TBB library for your new C++ projects – high-level STL-like parallel API. </li></ul><ul><li>For the IO-bounded Real-Time and/or Network Concurrent Programming, look at ACE Framework or use your native threads API. </li></ul><ul><li>Be aware of potential performance pitfalls like, cache locality and FSB saturation. </li></ul><ul><li>Benchmark everything! </li></ul>
  82. 82. Commercial Multi-core <ul><li>Commercial multi-core applications is not the future. </li></ul><ul><ul><li>It is NOW! </li></ul></ul>
  83. 83. Any Questions?
  84. 84. Thank you!