Multi-Threading

Post on 10-May-2015

2.641 views 11 download

Tags:

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

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

Multi-Threading

Po

we

red

by A

TC

www.bbd.co.za

.NET Multi-Threading Introductory UsageProven Practices

Overture

Po

we

red

by A

TC

www.bbd.co.za

DEMO

Hello to the threading world

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

Po

we

red

by A

TC

www.bbd.co.za

DEMO

Managing threads

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

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

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

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

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

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

Po

we

red

by A

TC

www.bbd.co.za

Similar usage to InterruptThrows – ThreadAbortExceptionDoes not wait for blocking

Abort

Po

we

red

by A

TC

www.bbd.co.za

DEMO

Using non-blocking management

Po

we

red

by A

TC

www.bbd.co.za

DEMO

Using the built in ThreadPools

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

Po

we

red

by A

TC

www.bbd.co.za

DEMO

Threaded controls in WinForms

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

Po

we

red

by A

TC

www.bbd.co.za

DEMO

Talking to the UI thread from a worker thread

Po

we

red

by A

TC

www.bbd.co.za

“Multi-threaded programming needs a little care”

Patricia Shanahan

Understatement?

Po

we

red

by A

TC

www.bbd.co.za

CostThread Safety

Race conditionsDead locks

Exception ManagementDebugging

Common Problems

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

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

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

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

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

Po

we

red

by A

TC

www.bbd.co.za

Exceptions are limited to a thread

Exceptions

try{}catch{}

MainChild

1

Po

we

red

by A

TC

www.bbd.co.za

DEMO

Debugging in Visual Studio

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

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

Po

we

red

by A

TC

www.bbd.co.za

Q&A