Multithreading.NET a practical perspective Peter Ibbotson.

Slides:



Advertisements
Similar presentations
Chapter 4 Threads Patricia Roy Manatee Community College, Venice, FL ©2008, Prentice Hall Operating Systems: Internals and Design Principles, 6/E William.
Advertisements

CS492B Analysis of Concurrent Programs Lock Basics Jaehyuk Huh Computer Science, KAIST.
Chapter 14 Multithreading Yingcai Xiao. Multithreading is a mechanism for performing two or more tasks concurrently.  In the managed world of the common.
IT Systems Multiprocessor System EN230-1 Justin Champion C208 –
Threads, SMP, and Microkernels Chapter 4. Process Resource ownership - process is allocated a virtual address space to hold the process image Scheduling/execution-
Threads in C# Threads in C#.
Chapter 4 Threads, SMP, and Microkernels Patricia Roy Manatee Community College, Venice, FL ©2008, Prentice Hall Operating Systems: Internals and Design.
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
1 Thread Pools Representation and Management of Data on the Internet.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
CPS110: Implementing threads/locks on a uni-processor Landon Cox.
Race Conditions CS550 Operating Systems. Review So far, we have discussed Processes and Threads and talked about multithreading and MPI processes by example.
Code Generation CS 480. Can be complex To do a good job of teaching about code generation I could easily spend ten weeks But, don’t have ten weeks, so.
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
50.003: Elements of Software Construction Week 5 Basics of Threads.
Welcome To. Improving Remote File Transfer Speeds By The Solution For: %
Rensselaer Polytechnic Institute CSCI-4210 – Operating Systems David Goldschmidt, Ph.D.
1 Computer System Overview Chapter 1. 2 n An Operating System makes the computing power available to users by controlling the hardware n Let us review.
Contact Information Office: 225 Neville Hall Office Hours: Monday and Wednesday 12:00-1:00 and by appointment.
Overview of Threading with the.NET Framework  Wallace B. McClure  Scalable Development, Inc. Scalable Development, Inc. Building systems today that perform.
Threads some important concepts Simon Lynch
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Operating Systems Lecture 2 Processes and Threads Adapted from Operating Systems Lecture Notes, Copyright 1997 Martin C. Rinard. Zhiqing Liu School of.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
Real Time Operating Systems Lecture 10 David Andrews
Processes and Threads Processes have two characteristics: – Resource ownership - process includes a virtual address space to hold the process image – Scheduling/execution.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
Threads, SMP, and Microkernels Chapter 4. Process Resource ownership - process is allocated a virtual address space to hold the process image Scheduling/execution-
Copyright 2006 by Timothy J. McGuire, Ph.D. 1 MIPS Assembly Language CS 333 Sam Houston State University Dr. Tim McGuire.
1 How will execution time grow with SIZE? int array[SIZE]; int sum = 0; for (int i = 0 ; i < ; ++ i) { for (int j = 0 ; j < SIZE ; ++ j) { sum +=
CPS110: Implementing threads Landon Cox. Recap and looking ahead Hardware OS Applications Where we’ve been Where we’re going.
Java Thread and Memory Model
1 Computer Systems II Introduction to Processes. 2 First Two Major Computer System Evolution Steps Led to the idea of multiprogramming (multiple concurrent.
Lecture on Central Process Unit (CPU)
Project 2 Overview (Threads in Practice) CSE451 Andrew Whitaker.
C H A P T E R E L E V E N Concurrent Programming Programming Languages – Principles and Paradigms by Allen Tucker, Robert Noonan.
Threaded Programming Lecture 1: Concepts. 2 Overview Shared memory systems Basic Concepts in Threaded Programming.
Copyright 2006 by Timothy J. McGuire, Ph.D. 1 MIPS Assembly Language CS 333 Sam Houston State University Dr. Tim McGuire.
Interrupts and Exception Handling. Execution We are quite aware of the Fetch, Execute process of the control unit of the CPU –Fetch and instruction as.
Safer Internet Day. What do you use the Internet for? watching TV shows watching online videos playing gamestalking to friends homeworkfinding out things.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Threads, SMP, and Microkernels Chapter 4. Processes and Threads Operating systems use processes for two purposes - Resource allocation and resource ownership.
CPS110: Implementing threads on a uni-processor Landon Cox January 29, 2008.
Today Threading, Cont. Multi-core processing. Java Never Ends! Winter 2016CMPE212 - Prof. McLeod1.
Java Thread Programming
Threads Some of these slides were originally made by Dr. Roger deBry. They include text, figures, and information from this class’s textbook, Operating.
Segments Introduction: slides minutes
Multi-processor Scheduling
Multi Threading.
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2002
Thread Fundamentals Header Advanced .NET Threading, Part 1
Mechanism: Limited Direct Execution
How will execution time grow with SIZE?
Multithreading .NET a practical perspective
Async or Parallel? No they aren’t the same thing!
Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2005
Threads, SMP, and Microkernels
Synchronization Issues
Processes and Threads.
Threading using C# and .Net
Thread Implementation Issues
Lecture Topics: 11/1 General Operating System Concepts Processes
Lecture 4- Threads, SMP, and Microkernels
Threads and Concurrency
Threads Chapter 4.
Background and Motivation
Chapter 3: Processes.
Threads in Java James Brucker.
Presentation transcript:

Multithreading.NET a practical perspective Peter Ibbotson

Why multi-thread?  With new dual core processors makes better use of the CPU  Keeps the User Interface responsive during long calculations.  Allows Asynchrous IO - Asynchronous Programming model (aka APM)  Single CPU systems can be slightly slower, but the user experience is better.

Why not multi-thread?  It's hard to do right.  Really it is!  Generates Heisenbugs very easily  Synchronisation is hard  Often you don't really need it  Talking to Windows forms controls is tricky  Threads aren't cheap

Thread basics I  Threads aren't "free"  They get 1MB of address reserved for stack + 12KB of kernel-mode stack  Each DLL in the parent process gets called to say a new thread has been created  Each DLL also gets called when a thread is about to die.  Context switches save / restore registers (700 bytes on x86, 1240 on x64) and use a spinlock so take time.

Thread basics II  Create a tread using ThreadStart passing in a delegate to call:  Thread Worker=new Thread(new ThreadStart(StartMethod));  Start the thread using Thread.Start();  Stop a thread using Thread.Abort()  Suspend a thread using Thread.Suspend();  Wait for a thread to complete using Thread.Join();

Example  Notes  Parameterised threads aren't always a good idea particularly as they aren't type safe.  Often better to create a whole class with local variables that you initialise before you start the thread.

Variables and caches  Two threads share variables BUT the cache gets in the way. Each one may not see the same value.  internal sealed class CacheCoherencyProblem { private byte m_init=0; private Int32 m_value=0; public void Thread1(){ m_value=5; m_init=1;} public void Thread2(){ if (m_init==1) WriteLine(m_value);} } In theory if you run this it may display 0, but this depends on cachelines

Variables and caches step 1  CPU1 runs Thread1 CPU2 Thread2  internal sealed class CacheCoherencyProblem { private byte m_init=0; private Int32 m_value=0; public void Thread1(){ m_value=5; m_init=1;} public void Thread2(){ if (m_init==1) WriteLine(m_value);} } CPU2 reads a byte from memory and it's before m_value fields bytes in memory, so both of them get read into cache. So CPU2 has m_value already in cache

Variables and caches step 2  CPU1 runs Thread1 CPU2 Thread2  internal sealed class CacheCoherencyProblem { private byte m_init=0; private Int32 m_value=0; public void Thread1(){ m_value=5; m_init=1;} public void Thread2(){ if (m_init==1) WriteLine(m_value);} } CPU1 runs Thread1 and changes m_value to 5 but this stays in cache, the following m_init=1 line gets written straight out to main memory

Variables and caches step 3  CPU1 runs Thread1 CPU2 Thread2  internal sealed class CacheCoherencyProblem { private byte m_init=0; private Int32 m_value=0; public void Thread1(){ m_value=5; m_init=1;} public void Thread2(){ if (m_init==1) WriteLine(m_value);} } Now CPU2 reads in m_init sees it's set to 1 and reuses the m_value from cache so m_value contains 0 and that is whats displayed

Sorry No demonstration  Sadly I couldn't get something like this to fail reliably  There are work arounds  Use VolatileRead & Write  Better yet use the C# keyword volatile.  Or just ignore it and use either  System.Threading.Interlocked  Monitor class and C# lock

The better idea use the monitor class  Quick demo of the problem  Example 2

The better idea use the monitor class  Quick demo of the problem  Example 2  Hopefully that race condition printed bingo a few times  The solution is to use C# lock statement  Back to the example

Monitor class and lock statement private void SomeMethod() { lock(this) { …. Access object } } Private void SomeMethod() { Object temp=this; Monitor.enter(temp); try { ….Access object } finally { Monitor.Exit(temp); }

Using locks in the real world  Don't do too many locks (Prefer locking larger objects)  Beware of nesting too deeply  Beware of deadlocking. Thread A acquires locks in this order Lock 1,2. Thread B acquires locks in this order Lock 2,1. On a bad day thread A has 1 locked and is waiting for 2 to become free. This will never happen as Thread B has lock 2 and is waiting for lock 1

Reader writer locks  ReaderWriterLock gives many readers access but only one writer.  Vance Morrison has more on this from the performance point of view  Use his version if performance is a problem from:  06/03/28/ aspx

Thread pool  After all that don't create threads directly. They are quite expensive.  Use System.Threading.Threadpool instead.  The thread pool puts threads into two classes  Compute bound  IO bound  It adds threads to the pool in 500ms increments – See example (3)

Asynchronous Programming Model  It's a pattern for doing asynchronous callbacks when something completes (i.e. network, file io etc)  Always of the form BeginXxxx EndXxxx  BeginRead / EndRead for files  BeginConnect / EndConnect for sockets  Etc…  Always Call EndXxxx otherwise you'll leak  The callback is on a ThreadPool thread.  Time for an example (4)

Windows forms  An alternative to multi-threading  Use a modal dialog  Call DoEvents in loop while pooling the cancel button state.  Quick example (5)

Windows forms some VB6 tricks revisited  An alternative to multi-threading  Use a modal dialog  Call DoEvents in loop while pooling the cancel button state.  Quick example (5)  Other alternatives - use a WinForms timer and a state machine. The WinForms timer posts WM_TIMER messages on the main UI thread.

Sometimes even Microsoft go single threaded  Version 6 of the animation control stopped using a background worker thread now uses WM_TIMER  If the main window stops reading messages (DoEvents) there is a chance the animation control will stall trying to get the background colour  If the foreground process doesn't read messages then if another window sends a broadcast message, windows stops but the animation keeps running.  See

Windows forms and threads (Examples stolen from chris sells)  "Thou shalt not operate on a window from other than its creating thread”  This means you need to use  Invoke or  BeginInvoke and EndInvoke  These transfer control back to the UI thread.  s/ aspx has a load of details  Example 6 and 7

Windows forms and threads (Examples stolen from chris sells)  "Thou shalt not operate on a window from other than its creating thread”  This means you need to use  Invoke or  BeginInvoke and EndInvoke  These transfer control back to the UI thread.  Adding a Cancel button  Example 8

ComponentModel.BackgroundWorker  Use this for simple background tasks  Simple to use and doesn't require BeginInvoke and friends

Multiple UI threads  Useful for things like reports  Use Application.Run from a new thread.

Further resources  Chris Sells MSDN articles   Jeffrey Richter – CLR via C# (book)  Vance Morrison   Invoke and friends  has a load of details  This powerpoint is at 