Multi-Threading

30
For more information see www.bbd.co.za and www.drp.co.za Multi-Threading

description

Slide deck from my presentation on multi-threading with .NET. The presentation covers from beginner onwards and looks at current technologies (i.e. pre .NET 4.0) specifically. What makes this extra special is the entire process of how I prepared for it, from finding content to slide deck layout to presentation prep is documented at: http://www.sadev.co.za/content/how-i-build-presentations-series-index

Transcript of Multi-Threading

Page 1: Multi-Threading

For more information see www.bbd.co.za and www.drp.co.za

Multi-Threading

Page 2: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

.NET Multi-Threading Introductory UsageProven Practices

Overture

Page 3: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

DEMO

Hello to the threading world

Page 4: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

BlockingThread.Sleep & Join

Lockinglock, Mutex & Semaphore

SinglingEventWaitHandle & Wait/Pulse

Non-BlockingMemory Barrier, Interlocked & Volatile

Managing

Page 5: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

DEMO

Managing threads

Page 6: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

static void Main() { Thread t = new Thread (delegate() { Console.ReadLine(); }); t.Start(); t.Join(); // Wait until thread finishes /* Do next step */}

Join

Page 7: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

lock(locker){ gate.Add(primeCounter);}

Monitor.Enter(locker);try{ gate.Add(primeCounter);}finally{ Monitor.Exit(locker);}

Sugary lock

Page 8: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

Same as a lockAdvantage: Can work across processes, meaning

multiple applications can use a single mutex

Mutex

Page 9: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

static EventWaitHandle wh = new AutoResetEvent(false);

static void Main() { new Thread (Waiter).Start(); Thread.Sleep (1000); // Wait for some time... wh.Set(); // OK - wake it up}

static void Waiter() { Console.WriteLine("Waiting..."); wh.WaitOne(); // Wait for notification Console.WriteLine("Notified");}

Signalling

Page 10: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

lock (locker){ gate.Add(primeCounter);}

Thread.MemoryBarrier();try{ gate.Add(primeCounter);}finally{ Thread.MemoryBarrier();}

Memory Barrier

Page 11: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

static void Main() { Thread t = new Thread(delegate() { try { Thread.Sleep(Timeout.Infinite); // This is blocking } catch (ThreadInterruptedException) { Console.Write("Forcibly "); } Console.WriteLine("Woken!"); }); t.Start(); t.Interrupt(); }

Interrupt

Page 12: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

Similar usage to InterruptThrows – ThreadAbortExceptionDoes not wait for blocking

Abort

Page 13: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

DEMO

Using non-blocking management

Page 14: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

DEMO

Using the built in ThreadPools

Page 15: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

Single thread pool per processBuilt in logic to grow and shrink poolBuilt-in Limits

Worker threads – 25 per CPUI/O threads – 1000 per CPU

Thread Pools

Page 16: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

DEMO

Threaded controls in WinForms

Page 17: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

Forms Timer Timers Timer Threading Timer

Thread? UI UI or Worker Worker

Thread safe No Yes No

Object Model Yes Yes No

WinForm Req. Yes No No

Accurate No Yes Yes

State Support No No Yes

Schedule Support No No Yes

Inheritance Yes Yes No

Timers

Source Alex Calvo - http://msdn.microsoft.com/en-us/magazine/cc164015(printer).aspx

Page 18: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

DEMO

Talking to the UI thread from a worker thread

Page 19: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

“Multi-threaded programming needs a little care”

Patricia Shanahan

Understatement?

Page 20: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

CostThread Safety

Race conditionsDead locks

Exception ManagementDebugging

Common Problems

Page 21: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

1 Mb of Address space12k for kernel mode stackNotification of every DLL in the process

Threads are expensive

Page 22: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

Reads value (5)Adds 1 – (6)Assumes value 6

Reads value (6)Adds 1 – (7)Assumes value 7

Thread 1 Thread 2

Race Conditions

Page 23: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

If file does not existCreate itPopulate it with initial data

Read data from fileProcess dataWrite to file

Logical Process I

Page 24: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

If file does not existCreate itPopulate it with initial data (Write Lock)

Read data from file (Read Lock)Process dataWrite to file (Write Lock – if needed)Release locks

Logical Process II

Page 25: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

Creates fileLocks writerAttempts to lock

readerWaits…

Locks ReaderProcesses dataAttempts to lock writerWaits…

Thread 1 Thread 2

Dead Locks

Page 26: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

Exceptions are limited to a thread

Exceptions

try{}catch{}

MainChild

1

Page 27: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

DEMO

Debugging in Visual Studio

Page 28: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

Threads are expensive – use wisely Use managed threads over native threads. Use Timers or ThreadPool where possible.

Or the new parallel extensions in .NET 4.0 Avoid mutex, unless you need cross process. Avoid Thread.Abort as it can have high side effects Avoid Thread.Suspend/Resume as a blocking system

Rather use lock

Proven Practises I

Page 29: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

Be careful what you lock lock’s are type based shared across all AppDomains. Use static

as the solution this (instances) have a high chance of deadlocks

Use lock over Monitor If you must use Monitor, use try...finally

Inside a lock do as little as possible If you are doing math inside the lock rather change to

Interlocked Never perform long running operations on the UI thread

Proven Practises II

Page 30: Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

Q&A