Die Präsentation wird geladen. Bitte warten

Die Präsentation wird geladen. Bitte warten

Parallelprogrammierung mit der TPL und .NET 4.0

Ähnliche Präsentationen


Präsentation zum Thema: "Parallelprogrammierung mit der TPL und .NET 4.0"—  Präsentation transkript:

1 Parallelprogrammierung mit der TPL und .NET 4.0
Bernd Marquardt –

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

3 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

4 Einführung Intel Clock Speed Quelle: Intel, Wikipedia

5 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

6 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

7 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

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

9 Einführung – Amdahls Gesetz Sequentieller Code begrenzt das Speedup!
n = number of processors Tparallel = {(1-P) + P/n} Tserial Speedup = Tserial / Tparallel T serial 1.0/0.5 = 2.0 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!

10 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

11 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

12 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

13 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.

14 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

15 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.

16 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

17 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

18 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.

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

20 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.

21 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();

22 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

23 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

24 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.

25 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!

26 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

27 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); }

28 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!!!)

29 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

30 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); });

31 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.

32 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

33 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.

34 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

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

36 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.

37 Performance MatMult (2 Core)
Größe Sequentiell Parallel ms ms ms ms ms ms ms

38 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

39 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.

40 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…

41 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.

42 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 { … });

43 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

44 Tasks: WSQ

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

46 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.

47 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

48 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.

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

50 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… }

51 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)

52 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.

53 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?

54 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.

55 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

56 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!

57 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)

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

59 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.

60 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

61 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

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

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

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

65 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.

66 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

67 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.

68 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

69 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.

70 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

71 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

72 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.

73 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

74 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.

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

76 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)

77 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   

78 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

79 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.

80 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

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

82 Testen und Debuggen Performance-Tests mit Visual Studio

83 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.

84 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

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

86 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,…

87 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.

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

89 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.

90 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

91 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.

92 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

93 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!

94 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.

95 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

96 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

97 Weitere Info‘s

98 Links: OpenMP: http://www.openmp.org
MPICH2: Parallel Extensions for the .NET Framework (Juni CTP):

99 ? FRAGEN


Herunterladen ppt "Parallelprogrammierung mit der TPL und .NET 4.0"

Ähnliche Präsentationen


Google-Anzeigen