Parallelprogrammierung mit der TPL und .NET 4.0

Slides:



Advertisements
Ähnliche Präsentationen
Software Assurance Erweiterte Software Assurance Services
Advertisements

der Universität Oldenburg
Multithreading mit .NET Jetzt besonders günstig in allen Sprachen
SQL Server 2005.NET Integration Sebastian Weber Developer Evangelist Microsoft Deutschland GmbH.
Was ist neu in VS 2003 ? Ein Überblick. Bernd Marquardt Software & Consulting
Suche in Texten (Stringsuche )
Name des Vortragenden Klasse Ort / tt.mm.jjjj Beschreibung Zentraleinheit CPU, Motherbord, RAM.
Ausnahmen HS Merseburg (FH) WS 06/07.
Atmel AVR JTAG Einführung
Abstrakte Klassen.
Ein Beispiel in Java.
Klassenvariable. Da man für jede Kuh bzw. jede Henne auf dem Markt den gleichen Preis für ein Liter Milch, bzw. den gleichen Preis für ein Ei bekommt,
Konstruktoren.
Polymorphie (Vielgestaltigkeit)
Dynamischer Speicher. In einer Funktion wird z.B. mit der Deklaration int i; Speicher auf dem sogenannten Stack reserviert. Wenn die Funktion verlassen.
XINDICE The Apache XML Project Name: Jacqueline Langhorst
OpenMP Präsentation im Rahmen des Seminars
Introducing the .NET Framework
Vorlesung, Wintersemester 2009/10M. Schölzel 1 Optimierungstechniken in modernen Compilern Optimierungstechniken für SMP- Architekturen.
Vortrag III Hier in der Vorlesungszeit! Anwesenheitspflicht Jede Gruppe hat 6 Minuten! Stellt eure GUI vor –was ihr besonderes gemacht habt –Spektakuläre.
Einführung in Visual C++
DVG Klassen und Objekte
EDV Parallelprogrammierung1 Parallelprogrammierung mit JAVA.
DVG Kommentare 1 Kommentare. 2 Kommentare Es gibt zwei Arten von Kommentaren: einzeilige Kommentare // der Kommentar geht bis zum Ende der Zeile.
Der VFP Debugger - Coverage und Profiling. © 1999 TMN-Systemberatung GmbH Der VFP Debugger n Neues Aussehen, eigene Task n Erweiterte Möglichkeiten n.
Erstellen von WebServices mit Visual FoxPro 9.0
Wizards & Builders GmbH Schulung Visual SourceSafe für Visual FoxPro Norbert Abb W&B.
Uwe Habermann Venelina Jordanova dFPUG – Silverlight Wizard.
Error Handling unter Visual FoxPro. © 1999 TMN-Systemberatung GmbH ON ERROR n ON ERROR DO ERRHAND WITH error(), sys(16), message(), lineno(1) – Globales.
Uwe Habermann WPF Avalon Formulare aus VFP verwenden Venelina Jordanova
MSDN Webcast: VB. NET für Einsteiger und Umsteiger Einführung in VB
Presenter: Daniel Walzenbach Technologieberater
Multitasking im Betriebssystem
Einstellungen im Web für Outlook
Duo- und Quad Prozessor-Architektur
Entwicklung verteilter Anwendungen I, WS 13/14 Prof. Dr. Herrad Schmidt WS 13/14 Kapitel 4 Folie 2 Message Passing mittels Sockets (1) s.a.
Name des Vortragenden Klasse Ort / tt.mm.jjjj Beschreibung Zentraleinheit CPU, Motherbord, RAM.
Silverlight Eine Einführung. Agenda 1.Was ist Silverlight? 2.Die Silverlight Philosophie 3.Vorstellung des Szenarios 4.Einführendes Beispiel 5.Konzepte.
Clustered Neuronal Network A C#.NET project for Compute Cluster Server 2003.
Programmierung paralleler Algorithmen mit MPI
Systeme 1 Kapitel 4 Prozesse WS 2009/10.
SQL Server 2005 CLR-Integration
Einführung in die Programmiersprache C 3.Tag Institut für Mathematische Optimierung - Technische Universität Braunschweig.
Javakurs FSS 2012 Lehrstuhl Stuckenschmidt
Debugging in Lua Universität zu Köln Re-usable Content in 3D und Simulationssystemen Prof. Dr. Manfred Thaller Referent: Artur Wilke.
Black Box Algorithmen Hartmut Klauck Universität Frankfurt SS
Windows Presentation Foundation WS 2013/14 Prof. Dr. Herrad Schmidt
Windows Presentation Foundation, Vorlesung Wintersemester 2013/14 Prof. Dr. Herrad Schmidt WS 13/14 Kapitel 9 Folie 2 ADO.NET (1) Klassen für Zugriffe.
Parallel Matrix Multiplication
CGI (Common Gateway Interface)
Bernd Marquardt Software+Consulting. Einführung Download, Voraussetzungen, Installation Parallelerweiterungen für das Framework Schleifen parallelisieren.
Vortrag: Visual Basic Neuerungen Autor : Dennis Hoyer
Objectives Verstehen was unterDelegate verstanden wird
Learning By Doing Parallelverarbeitung Multithreading (Nebenläufigkeit) Alte Idee der Parallelverarbeitung statt rein sequentieller Prozesse Parallelverarbeitung.
Betriebssysteme Übung Tutorium „TLB & Virtual Memory“
JOMP
Parallelisierung für Multiprozessor-Maschinen Teil 2.
Parallelisierung für Multiprozessor-Maschinen
SFZ FN Sj. 13/14 Python 3 Rekursion Inf K1/2 Sj 13/14
Parallele Programmierung im.NET Framework Darmstadt, Präsentation am Beispiel von C-Sharp (C#)  Wichtige Grundlagen  Generika, Delegate, Lambda,
Mehrfachausführungen Schleifen in VB 2010 ee. Programmidee: Der Anwender gibt eine Zahl ein, und das Programm gibt die Mehrfachen dieser Zahl aus (das.
Autor: Timo Pagel Nutzung: Diese Lernkarten sind für die Nutzung mit OpenCards gedacht Siehe dazu
2 Datenabstraktion Geheimnisprinzip:
Microsoft Student Partner
Der Taskmanager ist Bestandteil des Betriebssystems, der als Prozessmanager Prozessmanager unter anderem die aktuell laufenden Programme und Prozesse.
Funktionen, Felder und Parameter- übergabe. Funktionsaufruf mit Feld als Parameter: Parameter = Name des Feldes.
Multiprocessing mit OpenMPI Marius Albath. Vorlesung Betriebssysteme, Was ist OpenMPI Was ist OpenMPI OpenMPI Standard Setup OpenMPI Standard.
© 2008 TravelTainment The Amadeus Leisure Group Thread-Programmierung im Qt-Framework Von: Simon Lubberich Erstbetreuer:
 Präsentation transkript:

Parallelprogrammierung mit der TPL und .NET 4.0 Bernd Marquardt – bm@go-sky.de

Agenda Einführung Schleifen parallelisieren Code-Bereiche parallelisieren Aufgaben parallelisieren Weitere spezielle Themen PLINQ, Exceptions, Cancelation, Containerklassen Testen und Debuggen Windows und Parallelprogrammierung Zusammenfassung

Einführung Bisher: Alle 2-3 Jahre wurden die CPU‘s doppelt so schnell Davon haben unsere Programme automatisch etwas Deutlich sichtbar bei mathematischen Berechnungen, weniger sichtbar bei UI-Angelegenheiten

Einführung Intel Clock Speed Quelle: Intel, Wikipedia

Einführung Prozessor-Takt bleibt bei 3 – 4 GHz stehen Mehr geht nicht: Kühlung wird schwierig Eigentlich müssten unsere CPU‘s jetzt ca. 100 GHz können Anzahl der Transistoren auf einem Chip steigt aber weiter an Resultat: Multi-Core CPU‘s kommen immer stärker Mehrere CPU‘s auf einem Chip

Einführung Programmierung für Multi-Core CPU‘s Multi-Processing (gibt uns das Betriebssystem) Multi-Threading (müssen wir im Moment noch selbst programmieren) Wir müssen unsere Programme anpassen, sonst haben wir nichts von dem Multi-Core CPU‘s in einer Anwendung

Einführung Andere Parallelisierungs-Technologien: Multithreading, Threadpool Managed und unmanaged Code OpenMP (C, C++) MPI (Message Passing Interface) (C, C++, FORTRAN) Jetzt auch managed für .NET  MPI.NET NEU: Parallel Extensions for .NET (TPL) Eine Erweiterung für C# und VB.NET Nur managed Code NEU: Parallel Pattern Library (PPL) Eine Erweiterung für C++ in VS 2010 Nur native Code

Einführung ACHTUNG: Normale Multithread-Programmierung ist NICHT einfach! Höherer Aufwand Debugging Fehlersuche Testing Synchronisierung Planung

Einführung – Amdahls Gesetz Sequentieller Code begrenzt das Speedup! n = number of processors Tparallel = {(1-P) + P/n} Tserial Speedup = Tserial / Tparallel T serial 0.5 + 0.0 1.0/0.5 = 2.0 0.5 + 0.25 1.0/0.75 = 1.33 P/2 KEY POINTS • *********************************************************** SCRIPT One of the goals of a program that executes in parallel should be to increase performance as much as possible. Therefore, one might be tempted to think initially that by adding as much processors as possible performance will continue to increase. However, this is not completely true. Algorithms might be executed in parallel but up to some point. This is what is know as Amdahl’s law. He stated that if you have an algorithm that executes a serial process, the performance gain that you might obtain from running it in parallel relies heavily on the percentage of the algorithm that can be executed in parallel. Also, it is very important to take into consideration the overhead of parallel execution when creating and synchronizing threads. *********************************************************** POTENTIAL QUESTIONS NOTES P + O P/∞ … (1-P) (1-P) Sequentieller Code begrenzt das Speedup!

Einführung – Amdahls Gesetz Dies bedeutet, dass die parallelen Arbeitseinheiten groß genug sein müssen Ansonsten dauert die Thread-Initialisierung länger, als die Parallelisierung einbringt

Installation Nur Visual Studio 2010/.NET 4.0 NICHT mit VS 2008 (CLR 4 wird benötigt) Betriebssysteme: Windows Server 2003/2008/2008 R2 Windows XP Windows Vista Windows 7

Einführung Die TPL nutzt Threads aus dem .NET-ThreadPool Threads aus dem ThreadPool bedeutet: Schnelle Bereitstellung von Threads Dadurch sind auch kleinere Aufgaben gut zu parallelisieren Die Threads müssen aber an den Pool zurückgegeben werden

demo TestThreadPool 3/28/2017 1:58 PM © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Parallelerweiterungen für Linq Es gibt zwei Möglichkeiten: System.Linq.ParallelEnumerable-Klasse AsParallel-Erweiterungsmethode Ziel: Parallele Datenabfragen mit Linq Sehr einfach WAS-Programmierung statt WIE-Programmierung

Demo 3, ParallelBabyNames 3/28/2017 1:58 PM Demo 3, ParallelBabyNames demo © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Schleifen parallelisieren Wichtige Klasse: System.Threading.Tasks.Parallel Schleifen werden aufgeteilt auf mehrere Threads aus dem ThreadPool Das geht nur, wenn die einzelnen Schleifendurchläufe unabhängig voneinander sind Problem z.B.: a[i] = a[i – 1] * 2

Schleifen parallelisieren WICHTIG: „Nach“ der Schleife werden alle Threads synchronisiert, welche die Schleife abgearbeitet haben In der Schleife können Variablen deklariert werden, die „thread-local“ sind Die Laufvariable darf nicht als lokale Variable deklariert werden

demo Demo 4, Demo 5, Demo 6 3/28/2017 1:58 PM © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Schleifen parallelisieren Auch foreach-Schleifen können parallelisiert werden Die Reihenfolge der Schleifendurchläufe ist nicht deterministisch

3/28/2017 1:58 PM Demo 4A demo © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Schleifen parallelisieren Achtung: Bei „unausgewogenen“ Schleifen muss etwas mehr in der Bibliothek passieren Beispiel: for(int i = 0; i < 1000; i++) { if(i < 500) DoLongCalculation(); } else DoShortCalculation();

Schleifen parallelisieren Diese Schleife wird nicht „halbiert“ Es werden kleine Arbeitseinheiten gemacht Sobald ein Thread mit einer Arbeitseinheit fertig ist, bekommt er die nächste, bis die Arbeit komplett erledigt ist  Schleifen-Partitionierung Das implementierte Standard-Verfahren ist sehr leistungsfähig

Schleifen: Eigene Partitionierung Man kann eigene Partitionierungsverfahren implementieren Interessant, bei Schleifen mit… …sehr kleinem Schleifen-Body …extrem unausgewogenen Schleifen Performance ist abhängig von einer vernünftigen Schleifen-Partitionierung

demo Partitioner 3/28/2017 1:58 PM © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Probleme mit Schleifen Achtung bei schreibendem Zugriff auf Klassenvariablen oder statischen Variablen Keine Fehlermeldungen (vom Compiler, Runtime) Ergebnisse sind falsch ( „Data Race“) REGEL: Es darf nur ein Thread gleichzeitig schreibend zugreifen Ggf. synchronisieren, d.h., schreibende Zugriffe werden nacheinander abgewickelt Achtung: Performance!

Probleme mit Schleifen Schleifendurchläufe sind nicht unabhängig voneinander D.h., in Schleifendurchlauf #i wird auf Daten zugegriffen, die im Schleifendurchlauf #j berechnet werden, wobei gilt: i != j Z.B.: a[i] = a[i-1] + 1 Abhilfe: Den Algorithmus ändern Werte, die in der Schleife benötigt werden, möglichst aus dem Index berechnen

Aggregationen Zusammenfassen von Ergebnissen Achtung: Meistens ist Locking erforderlich Typischer Anwendungsfall: double dSum = 0.0; for(int i = 0; i < 1000; i++) { dSum += Math.Sqrt(i); }

Aggregationen Zwischenwerte werden über den sog. ThreadLocalState weitergegeben Ablauf: Vor der Schleifenabarbeitung: LocalState initialisieren Schleifenteil abarbeiten: Im Thread rechnen, LocalState benutzen Nach der Abarbeitung der Teilschleife: Aggregation (Zusammenfassung) der Ergebnisse (Achtung: Locking!!!)

Aggregationen Das Ziel ist, möglichst WENIG Locking-Operationen durchzuführen Möglichkeit #1: In jedem Schleifendurchlauf beim Zugriff (Addition) auf dSum findet ein Lock statt Möglichkeit #2: Zwischensumme einer Arbeitseinheit ermitteln, Zwischensumme mit Locking zu dSum addieren

Aggregationen int iSum = 0; Parallel.For(0, 1000, // From, To () => 0, // Init // (Laufvariable, ParallelLoopState, ThreadLocalState) (i, pls, tls) => { // Loop body tls += i; return tls; }, (partSum) => { // Aggregation Interlocked.Add(ref iSum, partSum); });

3/28/2017 1:58 PM Agg1, Agg2 demo © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Schleifen abbrechen Wenn mehrere Threads für die Schleife parallel laufen, dann müssen alle Threads beendet werden Klasse ParallelLoopResult benutzen Berechnung beendet? Klasse ParallelLoopState enthält Break-Methode und eine Stop-Methode Alle Threads werden beendet

demo LoopBreakTest 3/28/2017 1:58 PM © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Tipps und Tricks Parallel.For und Parallel.ForEach: (Anzahl der Durchläufe * Dauer) muss groß genug sein Nicht vergessen: Amdahl‘s Gesetz! Möglichst wenig Synchronisierung verwenden

Beispiele und Performance Innere und äußere Schleife Schleifendurchläufe mit stark unterschiedlicher Dauer Matrixmultiplikation Primzahlen berechnen

InnerOuter, MatMult, PrimeSeq, PrimePar 3/28/2017 1:58 PM InnerOuter, MatMult, PrimeSeq, PrimePar demo © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Performance MatMult (2 Core) Größe Sequentiell Parallel 5 0.0017 0.0223 ms 10 0.0111 0.0254 ms 25 0.1687 0.1830 ms 50 1.3953 1.2970 ms 100 11.207 9.300 ms 250 185.41 94.81 ms 500 1950.8 978.0 ms

Anzahl der Threads Die Anzahl der zu verwendenden Threads wird mit der ParallelOptions–Klasse definiert MaxDegreeOfParallelism = -1  Alle Kerne und Prozessoren werden ausgenutzt In bestimmten Fällen kann es auch sinnvoll sein, die Anzahl der benutzten Threads auf > Kerne * Prozessoren zu setzen

3/28/2017 1:58 PM Demo2010_1 demo © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Codeblöcke parallelisieren Unabhängiger Code kann parallel ausgeführt werden Häufigstes Problem: Gleichzeitiger Zugriff auf die gleichen Daten (schreibend) Ohne Nachdenken geht da gar nichts! Wichtige Methode: Parallel.Invoke Auch hier: Unterschiedliche Schreibweisen möglich…

3/28/2017 1:58 PM Demo 7, Demo 8 demo © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Die Klasse Task Die Task-Klasse wird benötigt, um erweiterte Parallelisierungprobleme zu lösen Vergleichbar mit der ThreadPool-Klasse: …ist ähnlich wie: ThreadPool.QueueUserWorkItem(delegate { … }); Task.Factory.StartNew(delegate { … });

Tasks Die TPL benutzt nun den .NET ThreadPool als Standard-Scheduler Der ThreadPool hat mehrere Vorteile: Work-stealing queues werden intern in der TPL benutzt Hill-climbing-Methoden, wurden eingeführt, um die optimale Thread-Anzahl zu ermitteln Synchronisierungsmechanismen (wie SpinWait und SpinLock) werden intern verwendet

Tasks: WSQ

Die Klasse Task Wichtige Features: Synchronisierung von parallelen Ausführungseinheiten Task.Wait(), WaitAll(), WaitAny() Abbrechen von Ausführungseinheiten  Cancelation Framework

3/28/2017 1:58 PM Demo 10, Demo 11 demo © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Tasks und Parameter Übergabe von Parametern im Funktionsaufruf möglich Achtung: Seiteneffekte, wenn man es falsch macht Übergabe der Parameter mit Parametern der Lambda-Funktion

Demo 12_Falsch, Demo 12_Correct 3/28/2017 1:58 PM Demo 12_Falsch, Demo 12_Correct demo © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Task-Parameter Tasks können kontrolliert werden… …Created …WaitingForActivation …WaitingToRun …RanToCompletion …Canceled …Faulted …WaitingForChildrenToComplete

Tasks in Schleifen Tasks sind gut in sehr unausgewogenen Schleifen for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) for(int k = 0; k < i; k++) for(int l = 0; l < k; l++) // Do Work… }

Tasks in Schleifen Lösung 1: Schleife (außen) mit Parallel.For parallelisieren Achtung: Die Schleifendurchläufe werden zum Schluss immer länger Der Scheduler kann die Teilschleifen nur schlecht aufteilen, so dass alle Prozessoren gleichmäßig ausgelastet sind Lösung: Schleifen „rückwärts“ laufen lassen und Tasks benutzen (Task mit dem beiden inneren Schleifen)

MuchLoops, MuchLoopsTask 3/28/2017 1:58 PM MuchLoops, MuchLoopsTask demo © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Die Klasse Task<TResult> Die Klasse ermöglicht die asynchrone Berechnung von Daten Wenn später dann die berechneten Daten weiter benutzt werden sollen, wird geprüft, ob die Berechnung bereits abgeschlossen ist Sonst wird gewartet…. = Synchronisierung Kann man Task<TResult>-Variablen in Anwendungen mit einer Benutzerschnittstelle benutzen?

Demo 13, Demo 14, FutureWinForms, …WPF, FutureWinForms2, …LINQ 3/28/2017 1:58 PM Demo 13, Demo 14, FutureWinForms, …WPF, FutureWinForms2, …LINQ demo © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Concurrent Exceptions In normalen, sequentiellen Anwendungen kann zu einer bestimmten Zeit maximal EINE Exception geworfen werden Bei parallelen Anwendungen können auch mehrere Exceptions zu einem Zeitpunkt geworfen werden Oft werden die Exceptions dann auch noch in einem anderen Thread verarbeitet, als in dem Thread, in dem sie geworfen wurden

Concurrent Exceptions Paralleler Code: Reihenfolge, mehrere Exceptions!! Darum gibt es einen anderen Exception-Mechanismus in den Parallel Extensions Wenn eine Exception im Parallel-Code auftritt, werden alle Threads - so schnell wie möglich - angehalten Achtung: In dieser Zeit können eventuell noch weitere Exceptions auftreten!

Concurrent Exceptions Alle aufgetretenen Exceptions werden in einem Objekt der Klasse System.Threading.AggregateException eingesammelt Wenn alle Threads angehalten sind, dann wird die AggregateException neu geworfen und kann bearbeitet werden Die einzelnen Exceptions können über das Property InnerExceptions abgefragt werden (eine Collection der aufgetretenen Exceptions)

Concurrent Exceptions Welche Klassen werfen AggregateException-Objekte? Die Parallel-Klasse Die Task-Klasse Die Task<TResult>-Klasse Parallel LINQ (Abfragen)

3/28/2017 1:58 PM Demo 15 demo © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Synchronisierung Die Synchronisierung soll den Zugriff auf begrenzte Resourcen des Rechners steuern, wenn mehrere Threads gleichzeitig darauf zugreifen wollen Variablen (RAM) Codeteile LPT-, COM- und USB-Schnittstellen

Synchronisierung Eine Synchronisierung beinhaltet immer die Gefahr eines „Deadlocks“ Thread A wartet auf die Resource Thread B hat die Resource in Benutzung Thread B wartet auf Thread A

Synchronisierung Allgemeine Regeln: Nicht zu viel synchronisieren  Langsam Nicht zu wenig synchronisieren  Falsch Die richtige Sychronisierungsmethode wählen Keine eigenen Synchronisierungselemente programmieren  Schwierig

Synchronisierung Standard-Synchronisierungsmechanismen: Monitor, lock (C#) Interlocked-Klasse Mutex WaitHandle

Synchronisierung Barrier CountDownEvent LazyInit<T> ManualResetEventSlim SemaphoreSlim SpinLock SpinWait WriteOnce<T> Collections (Stack, Queue, Dictionary)

demo ConcurQueue 3/28/2017 1:58 PM © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

TPL + UI Die goldene Regel gilt natürlich auch hier! WPF oder WinForms laufen im STA Sie dürfen nur aus dem Thread auf Controls zugreifen, im dem Sie die Controls erzeugt haben Ab Framework 2.0: Exception im Debug-Modus

demo TestWinForms 3/28/2017 1:58 PM © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

TPL + UI WindowsForms: Windows Presentation Foundation: Benutzung von InvokeRequired zum Test, ob der richtige Thread Benutzung von BeginInvoke zum Umschalten in den richtigen Thread Windows Presentation Foundation: Benutzung von Dispatcher.VerifyAccess oder Dispatcher.CheckAccess zum Test, ob der richtige Thread Benutzung von Dispatcher.Invoke zum Umschalten in den richtigen Thread

demo TestTPLWinForms 3/28/2017 1:58 PM © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Erweiterung der Tasks Erweiterungen zusätzlich zu ContinueWith: ContinueWhenAll ContinueWhenAny Leistungsfähiges Konzept für die Fortführung der Arbeit, wenn bestimmte Teilaufgaben erledigt sind

TaskScheduler Die alte Klasse TaskManager wurde ersetzt durch die TaskScheduler-Klasse Neue WorkStealing-Queues im ThreadPool TaskScheduler ist eine abstrakte Basisklasse Man kann davon ableiten und eigene TaskScheduler‘s programmieren Interessant für spezielle Szenarien Z.B.: spezielle Prioritätsverwaltung

demo TaskSchedulerTest 3/28/2017 1:58 PM © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

TaskScheduler Ein weiteres spezielles Szenario für die Benutzung eines TaskScheduler‘s: Zugriff auf das User Interface Die alte Regel gilt immer noch… Ablauf: Asynchrone Berechnung im Task Fortführung mit ContinueWith (z.B. Ergebnisausgabe) – aber im korrekten Thread-Kontext ( im UI-Thread) Früher: Benutzung von Invoke

demo Demo2010_Scheduler 3/28/2017 1:58 PM © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Cancellation Einfaches „Abschießen“ (Kill) von Threads ist keine gute Lösung Offene Dateien??? Locks??? Schreibende Zugriffe??? Genutzte Resourcen??? …???

Cancellation Das Beenden von Threads muss kooperativ erfolgen Der Thread kann nur an bestimmten Stellen beendet werden Der Thread kann selbst entscheiden, wann er beendet wird Abhängige Threads werden ebenfalls beendet Gutes Beispiel: BackgroundWorker-Control (ab .NET Framework 2.0)

Cancellation Anlegen eines CancellationTokenSource-Objektes Das CancellationToken-Objekt wird an alle Threads übergeben, die über das eine Source-Objekt beendet werden können In den Threads wird das Token-Objekt über das Property IsCancellationRequested abgefragt Alle Threads des Source-Objekts werden über die Cancel-Methode des Source-Objektes beendet   

Cancellation Ggf. wird dann aufgeräumt Nach dem Aufräumen wird aus dem Thread eine OperationCanceledException geworfen Diese kann im aufrufenden (Main-) Thread eingefangen und verarbeitet werden

CancelTest1, TaskCancel 3/28/2017 1:58 PM CancelTest1, TaskCancel demo © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Testen und Debuggen …ist in parallelen Programmen gar nicht so einfach Parallelprogrammierung hat meistens einen Grund: Performance-Steigerung Messgrößen sind also: Richtigkeit des Ergebnisses Ausführungszeit

Testen und Debuggen Häufiges Problem: Die Anwendung skaliert nicht mehr mit Erhöhung der Prozessoranzahl

Testen und Debuggen Performance-Tests mit Visual Studio

Visual Studio: TestPerf 3/28/2017 1:58 PM Visual Studio: TestPerf demo © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Debugging Es gibt zwei neue Debugging-Fenster in Visual Studio 2010 Fenster: Parallel Tasks Fenster: Parallel Stacks Für native und für managed Code Die Fenster können geöffnet werden, wenn ein Breakpoint angelaufen wurde Debug > Windows > Parallel Tasks Debug > Windows > Parallel Stacks

Debugging Parallel Tasks-Fenster: Unterstützung des Task-basierten Programmierens Auflistung aller Tasks Waiting, Running, Scheduled,… Ausgaben können konfiguriert und gruppiert werden

Debugging Parallel Stacks-Fenster: In modernen Anwendungen laufen oft mehrere Threads gleichzeitig Das Fenster zeigt die hierarchische Aufrufreihenfolge von Threads an …siehe Call-Stack (ohne Threading-Info‘s) Ausgaben können in unterschiedlicher Weise dargestellt werden TopDown, BottomUp, Zooming, Panning,…

Visual Studio: TestDebug 3/28/2017 1:58 PM Visual Studio: TestDebug demo © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Debugging Suche nach Deadlocks ist mit dem VS-Debugger möglich Benutzung des Parallel-Tasks-Fensters

Visual Studio: TestDead 3/28/2017 1:58 PM Visual Studio: TestDead demo © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Debugging Ausgaben werden meistens mit Console.WriteLine(…) gemacht Problem: Console.WriteLine(…) blockiert alle Threads, damit die Ausgabe auch lesbar sind Dadurch wird natürlich das „laufende“ Threading stark beeinflusst und es können nicht erwünschte Zustände entstehen Lösung: Console-Ausgabe entkoppeln

3/28/2017 1:58 PM ConsoleEx demo © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

DataBinding mit Threading Eigentlich sollte DataBinding mit MultiThreading Schwierigkeiten machen D.h., die Business-Logik läuft in einem anderen Thread, als das User Interface Das ist auch so – bis einschließlich .NET Framework 2.0 Siehe Beispiel

WPF-DataBinding mit Threading Bei WPF hat Microsoft etwas weiter gedacht… Vor der Ausführung des Bindings wird geprüft, ob der richtige Thread benutzt wird Wenn nicht, wird mit Dispatcher.Invoke umgeschaltet DataBinding mit WPF und MultiThreading ist also kein großes Problem …ab einschl. .NET Framework 3.0 Funktioniert nicht bei Windows Forms!

demo Test_Binding_WPF 3/28/2017 1:58 PM © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Zusammenfassung Es gibt neue Möglichkeiten, um Code zu parallelisieren Wir müssen keine Threads mehr explizit erzeugen Schleifen sind einfach zu parallelsieren Code ist besser zu lesen, als mit einzelnen Threads Auch Codeblöcke kann man einfach paralellisieren

Zusammenfassung Trotzdem gibt es Fälle, bei denen eine Parallelisierung nichts bringt Testen, Prototyp erstellen Ggf. seriellen Code verwenden Die Klassen Task und Task<T> ermöglichen die präzisere Steuerung des parallelen Codes Parallel Linq bietet einfachere Möglichkeiten der parallelen Programmierung, als die bisherige Anwendung von normalen Threads

Weitere Info‘s

Links: OpenMP: http://www.openmp.org MPICH2: http://www.mcs.anl.gov/research/projects/mpich2/ Parallel Extensions for the .NET Framework (Juni CTP): http://www.microsoft.com/downloads/details.aspx?FamilyID=e848dc1d-5be3-4941-8705-024bc7f180ba&displaylang=en

? FRAGEN