SlideShare a Scribd company logo
Parallel Programming Patterns


                Аудиторія: розробники

                Олександр Павлишак, 2011
                pavlyshak@gmail.com
Зміст
-   Тренд
-   Основні терміни
-   Managing state
-   Паралелізм
-   Засоби
Вчора
Сьогодні
Завтра
Що відбувається?
-   Ріст частоти CPU вповільнився
-   Через фізичні обмеження
-   Free lunch is over
-   ПЗ більше не стає швидшим саме по собі
Сучасні тренди
- Manycore, multicore
- GPGPU, GPU acceleration, heterogeneous
  computing
- Distributed computing, HPC
Основні поняття
- Concurrency
  - Many interleaved threads of control
- Parallelism
  - Same result, but faster
- Concurrency != Parallelism
  - It is not always necessary to care about concurrency
    while implementing parallelism
- Multithreading
- Asynchrony
Задачі
- CPU-bound
  - number crunching
- I/O-bound
  - network, disk
Стан
- Shared
  - accessible by more than one thread
  - sharing is transitive
- Private
  - used by single thread only
Task-based program

         Application

       Tasks (CPU, I/O)

Runtime (queuing, scheduling)

Processors (threads, processes)
Managing state
Isolation
- Avoiding shared state
- Own copy of state
- Examples:
  - process isolation
  - intraprocess isolation
  - by convention
Immutability
-   Multiple read -- not a problem!
-   All functions are pure
-   Requires immutable collections
-   Functional way: Haskell, F#, Lisp
Synchronization
- The only thing that remains to deal with
  shared mutable state
- Kinds:
  - data synchronization
  - control synchronization
Data synchronization
- Why? To avoid race conditions and data
  corruption
- How? Mutual exclusion
- Data remains consistent
- Critical regions
  - locks, monitors, critical sections, spin locks
- Code-centered
  - rather than associated with data
Critical region
|Thread 1               |Thread 2
|// ...                 |// ...
|lock (locker)          |
|{                      |
|   // ...              |
|   data.Operation();   |
|   // ...              |
|}                      |
|// ...                 |lock (locker)
|                       |{
|                       |   // ...
|                       |   data.Operation();
                        |   // ...
Control synchronization
- To coordinate control flow
  - exchange data
  - orchestrate threads
- Waiting, notifications
  - spin waiting
  - events
  - alternative: continuations
Three ways to manage state
- Isolation: simple, loosely coupled, highly
scalable, right data structures, locality
- Immutability: avoids sync
- Synchronization: complex, runtime overheads,
contention

- in that order
Паралелізм
Підходи до розбиття задач
- Data parallelism
- Task parallelism
- Message based parallelism
Data parallelism
How?

- Data is divided up among hardware processors
- Same operation is performed on elements
- Optionally -- final aggregation
Data parallelism
When?

- Large amounts of data
- Processing operation is costly
- or both
Data parallelism
Why?

- To achieve speedup

- For example, with GPU acceleration:
  - hours instead of days!
Data parallelism
Embarrassingly parallel problems
- parallelizable loops
- image processing



Non-embarrassingly parallel problems
- parallel QuickSort
Data parallelism
                               ...
                         ...


  Thread 1    Thread 2
Data parallelism
Structured parallelism

- Well defined begin and end points
- Examples:
  - CoBegin
  - ForAll
CoBegin

var firstDataset = new DataItem[1000];
var secondDataset = new DataItem[1000];
var thirdDataset = new DataItem[1000];

Parallel.Invoke(
    () => Process(firstDataset),
    () => Process(secondDataset),
    () => Process(thirdDataset)
    );
Parallel For

var items = new DataItem[1000 * 1000];
// ...
Parallel.For(0, items.Length,
    i =>
        {
            Process(items[i]);
        });
Parallel ForEach

var tickers = GetNasdaqTickersStream();
Parallel.ForEach(tickers,
    ticker =>
        {
            Process(ticker);
        });
Striped Partitioning
                           ...




    Thread 1    Thread 2
Iterate complex data structures

var tree = new TreeNode();
// ...
Parallel.ForEach(
    TraversePreOrder(tree),
    node =>
        {
            Process(node);
        });
Iterate complex data
                Thread 1




                Thread 2




         ...
Declarative parallelism
var items = new DataItem[1000 * 1000];
// ...
var validItems =
    from item in items.AsParallel()
    let processedItem = Process(item)
    where processedItem.Property > 42
    select Convert(processedItem);

foreach (var item in validItems)
{
    // ...
}
Data parallelism
Challenges

-   Partitioning
-   Scheduling
-   Ordering
-   Merging
-   Aggregation
-   Concurrency hazards: data races, contention
Task parallelism
How?

- Programs are already functionally partitioned:
statements, methods etc.
- Run independent pieces in parallel
- Control synchronization
- State isolation
Task parallelism
Why?

- To achieve speedup
Task parallelism
Kinds
- Structured
  - clear begin and end points
- Unstructured
  - often demands explicit synchronization
Fork/join
-   Fork: launch tasks asynchronously
-   Join: wait until they complete
-   CoBegin, ForAll
-   Recursive decomposition
Fork/join
       Task 1



               Task 2



      Task 3




Seq                     Seq
Fork/join


Parallel.Invoke(
    () => LoadDataFromFile(),
    () => SavePreviousDataToDB(),
    () => RenewOtherDataFromWebService());
Fork/join
Task loadData =
    Task.Factory.StartNew(() => {
        // ...
    });
Task saveAnotherDataToDB =
    Task.Factory.StartNew(() => {
        // ...
    });
// ...
Task.WaitAll(loadData, saveAnotherDataToDB);
// ...
Fork/join
void Walk(TreeNode node) {
  var tasks = new[] {
      Task.Factory.StartNew(() =>
          Process(node.Value)),
      Task.Factory.StartNew(() =>
          Walk(node.Left)),
      Task.Factory.StartNew(() =>
          Walk(node.Right))
  };
  Task.WaitAll(tasks);
}
Fork/join recursive


       Root    Node

               Left
Seq    Left                 Seq
               Right

       Right   Node

               Left

               Right
Dataflow parallelism: Futures
Task<DataItem[]> loadDataFuture =
    Task.Factory.StartNew(() =>
    {
        //...
        return LoadDataFromFile();
    });

var dataIdentifier = SavePreviousDataToDB();
RenewOtherDataFromWebService(dataIdentifier);
//...
DisplayDataToUser(loadDataFuture.Result);
Dataflow parallelism: Futures

        Future




Seq              Seq     Seq
Dataflow parallelism: Futures

                                  Future

                         Future


                Future


Seq       Seq               Seq    Seq     Seq
Continuations

                       Task
                Task

       Task



Seq           Seq             Seq
Continuations
var loadData = Task.Factory.StartNew(() => {
        return LoadDataFromFile();
    });

var writeToDB = loadData.ContinueWith(dataItems =>
    {
        WriteToDatabase(dataItems.Result);
    });

var reportToUser = writeToDB.ContinueWith(t =>
    {
        // ...
    });
reportProgressToUser.Wait();
Producer/consumer
                   pipeline


reading           parsing            storing

                            parsed
          lines                                DB
                             lines
Producer/consumer
         pipeline

lines



        parsed
         lines




                 DB
Producer/consumer
var lines =
    new BlockingCollection<string>();

Task.Factory.StartNew(() =>
  {
    foreach (var line in File.ReadLines(...))
        lines.Add(line);
    lines.CompleteAdding();
  });
Producer/consumer
var dataItems =
  new BlockingCollection<DataItem>();

Task.Factory.StartNew(() =>
    {
        foreach (var line in
          lines.GetConsumingEnumerable()
        )
            dataItems.Add(Parse(line));
        dataItems.CompleteAdding();
    });
Producer/consumer
var dbTask = Task.Factory.StartNew(() =>
    {
        foreach (var item in
          dataItems.GetConsumingEnumerable()
        )
            WriteToDatabase(item);
    });

dbTask.Wait();
Task parallelism
Challenges

- Scheduling
- Cancellation
- Exception handling
- Concurrency hazards: deadlocks, livelocks,
priority inversions etc.
Message based parallelism
- Accessing shared state vs. local state
- No distinction, unfortunately
- Idea: encapsulate shared state changes into
  messages
- Async events
- Actors, agents
Засоби
Concurrent data structures
-   Concurrent Queues, Stacks, Sets, Lists
-   Blocking collections,
-   Work stealing queues
-   Lock free data structures
-   Immutable data structures
Synchronization primitives
-   Critical sections,
-   Monitors,
-   Auto- and Manual-Reset Events,
-   Coundown Events,
-   Mutexes,
-   Semaphores,
-   Timers,
-   RW locks
-   Barriers
Thread local state
- A way to achieve isolation


var parser = new ThreadLocal<Parser>(
    () => CreateParser());

Parallel.ForEach(items,
    item => parser.Value.Parse(item));
Thread pools
ThreadPool.QueueUserWorkItem(_ =>
    {
        // do some work
    });
Async
Task.Factory.StartNew(() =>
    {
        //...
        return LoadDataFromFile();
    })
    .ContinueWith(dataItems =>
        {
            WriteToDatabase(dataItems.Result);
        })
    .ContinueWith(t =>
        {
            // ...
        });
Async
var dataItems =
    await LoadDataFromFileAsync();

textBox.Text = dataItems.Count.ToString();

await WriteToDatabaseAsync(dataItems);

// continue work
Технології
-   TPL, PLINQ, C# async, TPL Dataflow
-   PPL, Intel TBB, OpenMP
-   CUDA, OpenCL, C++ AMP
-   Actors, STM
-   Many others
Підсумок
-   Програмування для багатьох CPU
-   Concurrency != parallelism
-   CPU-bound vs. I/O-bound tasks
-   Private vs. shared state
Підсумок
- Managing state:
  - Isolation
  - Immutability
  - Synchronization
     - Data: mutual exclusion
     - Control: notifications
Підсумок
- Паралелізм:
  - Data parallelism: scalable
  - Task parallelism: less scalable
  - Message based parallelism
Підсумок
- Data parallelism
  -   CoBegin
  -   Parallel ForAll
  -   Parallel ForEach
  -   Parallel ForEach over complex data structures
  -   Declarative data parallelism
- Challenges: partitioning, scheduling, ordering,
  merging, aggregation, concurrency hazards
Підсумок
- Task parallelism: structured, unstructured
  - Fork/Join
     - CoBegin
     - Recursive decomposition
  - Futures
  - Continuations
  - Producer/consumer (pipelines)
- Challenges: scheduling, cancellation,
  exceptions, concurrency hazards
Підсумок
- Засоби/інструменти
  -   Компілятори, бібліотеки
  -   Concurrent data structures
  -   Synchronization primitives
  -   Thread local state
  -   Thread pools
  -   Async invocations
  -   ...
Q/A

More Related Content

What's hot (13)

PPTX
Micro services workshop
Rajith Raveendranath
 
PDF
Developing for Node.JS with MySQL and NoSQL
John David Duncan
 
PDF
Stateful streaming data pipelines
Timothy Farkas
 
PDF
Bruce Momjian - Inside PostgreSQL Shared Memory @ Postgres Open
PostgresOpen
 
PDF
Tulsa techfest Spark Core Aug 5th 2016
Mark Smith
 
PDF
Oracle Join Methods and 12c Adaptive Plans
Franck Pachot
 
PPTX
Introduction to MapReduce and Hadoop
Mohamed Elsaka
 
PDF
CBO choice between Index and Full Scan: the good, the bad and the ugly param...
Franck Pachot
 
PDF
Pig
Vetri V
 
PDF
Percona Live 2012PPT: MySQL Query optimization
mysqlops
 
PPT
Anatomy of classic map reduce in hadoop
Rajesh Ananda Kumar
 
PDF
Event Processing and Integration with IAS Data Processors
Invenire Aude
 
PDF
Nhibernate Part 2
guest075fec
 
Micro services workshop
Rajith Raveendranath
 
Developing for Node.JS with MySQL and NoSQL
John David Duncan
 
Stateful streaming data pipelines
Timothy Farkas
 
Bruce Momjian - Inside PostgreSQL Shared Memory @ Postgres Open
PostgresOpen
 
Tulsa techfest Spark Core Aug 5th 2016
Mark Smith
 
Oracle Join Methods and 12c Adaptive Plans
Franck Pachot
 
Introduction to MapReduce and Hadoop
Mohamed Elsaka
 
CBO choice between Index and Full Scan: the good, the bad and the ugly param...
Franck Pachot
 
Pig
Vetri V
 
Percona Live 2012PPT: MySQL Query optimization
mysqlops
 
Anatomy of classic map reduce in hadoop
Rajesh Ananda Kumar
 
Event Processing and Integration with IAS Data Processors
Invenire Aude
 
Nhibernate Part 2
guest075fec
 

Viewers also liked (19)

PDF
Selecting BI Tool - Proof of Concept - Андрій Музичук
Igor Bronovskyy
 
PPT
Юрчук Андрій - Технологія Qt
Igor Bronovskyy
 
PDF
03 - chomu prohramisty ne testuiut - yurii chulovskyi - it event 2013 (5)
Igor Bronovskyy
 
PPT
Delivering business intelligence - Rava
Igor Bronovskyy
 
PDF
Usability - Sadygov
Igor Bronovskyy
 
PDF
11 - rozrobka prohramnoho zabezpechennia dlia vbudovanykh system - dmytro and...
Igor Bronovskyy
 
PPT
Mobile market - Ivasyshyn
Igor Bronovskyy
 
PPTX
From web to mobile - Василь Кричун
Igor Bronovskyy
 
PPTX
Code driven testing -- oleksandr pavlyshak
Igor Bronovskyy
 
PDF
Improve performance of developer - Khodak
Igor Bronovskyy
 
PPTX
Техніки швидкого читання - Любомир Ходак
Igor Bronovskyy
 
PPS
Strus
Igor Bronovskyy
 
PPT
Kordyak
Igor Bronovskyy
 
PDF
Правила конкурсного відбору для студентів ВНЗ м. Івано-Франківська у 2014 ро...
Igor Bronovskyy
 
PPT
огляд і особливості Symfony 2.0 - Анатолій Квасніков
Igor Bronovskyy
 
PPT
Скільки коштує проект і чому так.....
Igor Bronovskyy
 
PPTX
Aws - Marfej
Igor Bronovskyy
 
PDF
12 - gradle. evoliutsiia system avtomatychnoi zbirky - sviatoslav babych - it...
Igor Bronovskyy
 
PPTX
Побудова ефективної команди - Андрій Бабала
Igor Bronovskyy
 
Selecting BI Tool - Proof of Concept - Андрій Музичук
Igor Bronovskyy
 
Юрчук Андрій - Технологія Qt
Igor Bronovskyy
 
03 - chomu prohramisty ne testuiut - yurii chulovskyi - it event 2013 (5)
Igor Bronovskyy
 
Delivering business intelligence - Rava
Igor Bronovskyy
 
Usability - Sadygov
Igor Bronovskyy
 
11 - rozrobka prohramnoho zabezpechennia dlia vbudovanykh system - dmytro and...
Igor Bronovskyy
 
Mobile market - Ivasyshyn
Igor Bronovskyy
 
From web to mobile - Василь Кричун
Igor Bronovskyy
 
Code driven testing -- oleksandr pavlyshak
Igor Bronovskyy
 
Improve performance of developer - Khodak
Igor Bronovskyy
 
Техніки швидкого читання - Любомир Ходак
Igor Bronovskyy
 
Правила конкурсного відбору для студентів ВНЗ м. Івано-Франківська у 2014 ро...
Igor Bronovskyy
 
огляд і особливості Symfony 2.0 - Анатолій Квасніков
Igor Bronovskyy
 
Скільки коштує проект і чому так.....
Igor Bronovskyy
 
Aws - Marfej
Igor Bronovskyy
 
12 - gradle. evoliutsiia system avtomatychnoi zbirky - sviatoslav babych - it...
Igor Bronovskyy
 
Побудова ефективної команди - Андрій Бабала
Igor Bronovskyy
 
Ad

Similar to Parallel programming patterns - Олександр Павлишак (20)

PPTX
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
Panagiotis Kanavos
 
PPTX
Multi core programming 1
Robin Aggarwal
 
PDF
Arc 300-3 ade miller-en
lonegunman
 
PPT
Task and Data Parallelism
Sasha Goldshtein
 
ZIP
.Net 4.0 Threading and Parallel Programming
Alex Moore
 
PPTX
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Panagiotis Kanavos
 
PDF
Tim - FSharp
d0nn9n
 
PDF
C# Advanced L04-Threading
Mohammad Shaker
 
PPTX
Parallel Processing
RTigger
 
PDF
Parallel Programming in .NET
SANKARSAN BOSE
 
PPTX
.NET Multithreading/Multitasking
Sasha Kravchuk
 
PDF
Concurrency and parallel in .net
Mohammad Hossein Karami
 
PPT
Parallel Programming and F#
llangit
 
PPT
MTaulty_DevWeek_Parallel
ukdpe
 
PPTX
Multi core programming 2
Robin Aggarwal
 
PPTX
Dot net parallelism and multicore computing
Aravindhan Gnanam
 
PDF
Ia+ threading
Cyrille Dupuydauby
 
PDF
I see deadlocks : Matt Ellis - Techorama NL 2024
citizenmatt
 
PPTX
What's new in Visual Studio 2012 General
Noam Sheffer
 
PPT
Overview Of Parallel Development - Ericnel
ukdpe
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
Panagiotis Kanavos
 
Multi core programming 1
Robin Aggarwal
 
Arc 300-3 ade miller-en
lonegunman
 
Task and Data Parallelism
Sasha Goldshtein
 
.Net 4.0 Threading and Parallel Programming
Alex Moore
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Panagiotis Kanavos
 
Tim - FSharp
d0nn9n
 
C# Advanced L04-Threading
Mohammad Shaker
 
Parallel Processing
RTigger
 
Parallel Programming in .NET
SANKARSAN BOSE
 
.NET Multithreading/Multitasking
Sasha Kravchuk
 
Concurrency and parallel in .net
Mohammad Hossein Karami
 
Parallel Programming and F#
llangit
 
MTaulty_DevWeek_Parallel
ukdpe
 
Multi core programming 2
Robin Aggarwal
 
Dot net parallelism and multicore computing
Aravindhan Gnanam
 
Ia+ threading
Cyrille Dupuydauby
 
I see deadlocks : Matt Ellis - Techorama NL 2024
citizenmatt
 
What's new in Visual Studio 2012 General
Noam Sheffer
 
Overview Of Parallel Development - Ericnel
ukdpe
 
Ad

Recently uploaded (20)

PPTX
Urban Hierarchy and Service Provisions.pptx
Islamic University of Bangladesh
 
PDF
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
PPTX
SYMPATHOMIMETICS[ADRENERGIC AGONISTS] pptx
saip95568
 
PPTX
Iván Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 
PDF
Supply Chain Security A Comprehensive Approach 1st Edition Arthur G. Arway
rxgnika452
 
PPTX
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
PDF
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
PPTX
A Case of Identity A Sociological Approach Fix.pptx
Ismail868386
 
DOCX
ANNOTATION on objective 10 on pmes 2022-2025
joviejanesegundo1
 
PPTX
Elo the Hero is an story about a young boy who became hero.
TeacherEmily1
 
PPTX
ESP 10 Edukasyon sa Pagpapakatao PowerPoint Lessons Quarter 1.pptx
Sir J.
 
PDF
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
PPTX
How to use _name_search() method in Odoo 18
Celine George
 
PPTX
Elo the HeroTHIS IS A STORY ABOUT A BOY WHO SAVED A LITTLE GOAT .pptx
JoyIPanos
 
PPTX
Photo chemistry Power Point Presentation
mprpgcwa2024
 
PDF
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
PDF
Our Guide to the July 2025 USPS® Rate Change
Postal Advocate Inc.
 
PDF
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
DOCX
MUSIC AND ARTS 5 DLL MATATAG LESSON EXEMPLAR QUARTER 1_Q1_W1.docx
DianaValiente5
 
PDF
COM and NET Component Services 1st Edition Juval Löwy
kboqcyuw976
 
Urban Hierarchy and Service Provisions.pptx
Islamic University of Bangladesh
 
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
SYMPATHOMIMETICS[ADRENERGIC AGONISTS] pptx
saip95568
 
Iván Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 
Supply Chain Security A Comprehensive Approach 1st Edition Arthur G. Arway
rxgnika452
 
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
Gladiolous Cultivation practices by AKL.pdf
kushallamichhame
 
A Case of Identity A Sociological Approach Fix.pptx
Ismail868386
 
ANNOTATION on objective 10 on pmes 2022-2025
joviejanesegundo1
 
Elo the Hero is an story about a young boy who became hero.
TeacherEmily1
 
ESP 10 Edukasyon sa Pagpapakatao PowerPoint Lessons Quarter 1.pptx
Sir J.
 
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
How to use _name_search() method in Odoo 18
Celine George
 
Elo the HeroTHIS IS A STORY ABOUT A BOY WHO SAVED A LITTLE GOAT .pptx
JoyIPanos
 
Photo chemistry Power Point Presentation
mprpgcwa2024
 
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
Our Guide to the July 2025 USPS® Rate Change
Postal Advocate Inc.
 
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
MUSIC AND ARTS 5 DLL MATATAG LESSON EXEMPLAR QUARTER 1_Q1_W1.docx
DianaValiente5
 
COM and NET Component Services 1st Edition Juval Löwy
kboqcyuw976
 

Parallel programming patterns - Олександр Павлишак