Threads in C# Threads in C#.

Slides:



Advertisements
Similar presentations
1 Multithreaded Programming in Java. 2 Agenda Introduction Thread Applications Defining Threads Java Threads and States Examples.
Advertisements

Processes and Threads Chapter 3 and 4 Operating Systems: Internals and Design Principles, 6/E William Stallings Patricia Roy Manatee Community College,
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Chapter 14 Multithreading Yingcai Xiao. Multithreading is a mechanism for performing two or more tasks concurrently.  In the managed world of the common.
Chapter 4 Threads, SMP, and Microkernels Patricia Roy Manatee Community College, Venice, FL ©2008, Prentice Hall Operating Systems: Internals and Design.
Intro to Threading CS221 – 4/20/09. What we’ll cover today Finish the DOTS program Introduction to threads and multi-threading.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Concurrency…leading up to writing a web crawler. Web crawlers.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Chapter 11 Operating Systems
Java ThreadsGraphics Programming Graphics Programming: Java Threads.
1 Chapter 4 Threads Threads: Resource ownership and execution.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
A. Frank - P. Weisberg Operating Systems Introduction to Tasks/Threads.
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.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Collage of Information Technology University of Palestine Advanced programming MultiThreading 1.
Windows Programming Using C# Threading. 2 Contents Threading Thread class Interlocked class Monitor class Semaphore class Thread Pools.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Task Parallel Library (TPL)
Processes and Threads Processes have two characteristics: – Resource ownership - process includes a virtual address space to hold the process image – Scheduling/execution.
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Threads, SMP, and Microkernels Chapter 4. Process Resource ownership - process is allocated a virtual address space to hold the process image Scheduling/execution-
Background: Operating Systems Brad Karp UCL Computer Science CS GZ03 / M th November, 2008.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
Synchronizing threads, thread pools, etc.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
1 Threads, SMP, and Microkernels Chapter Multithreading Operating system supports multiple threads of execution within a single process MS-DOS.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading in JAVA
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Concurrency & Dynamic Programming.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9 th Edition Chapter 4: Threads.
Multithreading The objectives of this chapter are: To understand the purpose of multithreading To describe Java's multithreading mechanism.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
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.
Today Threading, Cont. Multi-core processing. Java Never Ends! Winter 2016CMPE212 - Prof. McLeod1.
Asynchronous Programming Writing Concurrent Code in C# SoftUni Team Technical Trainers Software University
Multithreading / Concurrency
Threading Lecture 11 M. Ipalakova.
Process Management Process Concept Why only the global variables?
Multi Threading.
Java Multithreading.
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2002
Thread Fundamentals Header Advanced .NET Threading, Part 1
Multithreaded Programming in Java
Critical sections, locking, monitors, etc.
Threads Chate Patanothai.
Chapter 4 Multithreading programming
CS18000: Problem Solving and Object-Oriented Programming
Multithreaded Programming
Lecture 4- Threads, SMP, and Microkernels
Threads and Concurrency
Multithread Programming
9. Threads SE2811 Software Component Design
NETWORK PROGRAMMING CNET 441
9. Threads SE2811 Software Component Design
9. Threads SE2811 Software Component Design
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Threads in C# Threads in C#

Benefits of using threads All modern computers has many cores (CPU’s) Dual core, quad core, etc. By dividing the program into more threads the program can utilize these cores The program will run faster One thread, means only one core used – other cores a idle Process request simultaneously on servers Client request arrive concurrently – and they are processed concurrently Keeping the user interface responsive Time-consuming tasks should execute in parallel with the UI thread. Threads in C#

Threads vs. processes Threads share memory Communication between threads One thread updates memory (data), another thread read this memory (data) Each thread has a separate call stack Processes do no share memory Communication between processes Sockets, etc. Operating systems has processes Threads and processes both run in parallel. This slide show is about threads, not processes. Threads in C#

The lifecycle of a thread More benefits of using threads Source: http://stackoverflow.com/questions/8966 636/thread-lifecycle-in-net A thread may be waiting for something to happen File to be read Incoming network requests Sleep() Wait() While one thread is waiting other thread should use the CPU The program will run faster Threads in C#

Interleaved concurrency vs. non-interleaved concurrency Instructions for each thread are interleaved (they take turns) T1, T1, T2, T2, T1, T2 Can be done with a single core If one thread is block other threads can continue running (Real) concurrency More threads are running in parallel, at the same time. Design has to be prepared for both interleaved and non-interleaved concurrency You never know how many cores your threads will have access to Threads in C#

Parallelism “Parallelism entails partitioning work to be done, running processing on those pieces concurrently, and joining the results. Parallelizing a problem generates concurrency” Hillar: Professional Parallel Programming with C#, Wrox 2011, page 19 Correctness For all different number of cores, and possible interleaving, the result must be correct. That is hard! Requires a lot of thinking when designing!! Threads in C#

Class Thread, construction + starting Thread(ThreadStart start) Delegate void ThreadStart() This constructor works with any void method with no parameters, void M() The method can be static or not Starting: call Start() Examples: TryThread Source http://msdn.microsoft.com/en- us/library/System.Threading.Thread.Thread(v=vs.110).aspx Threads in C#

Thread constructors with lambda expressions Using a lambda expression as the parameter to the Thread constructor you can give any number of parameters to the called method and the parameters can be typed (not object) Examples: TryThread Threads in C#

Name property Threads have names Thread tr = new Thread(…) Good for debugging etc. Thread tr = new Thread(…) tr.Name = ”some name”; Thread.CurrentThread.Name, used in the working method CurrentThread is a static property of Thread Example: TryThread Threads in C#

Sleep method Thread.sleep(500); Example: TryThread Suspends the current thread for 500 milliseconds. The thread will not be scheduled for execution for 500 milliseconds Static method in the Thread class Example: TryThread Threads in C#

Join method someThread.Join() Blocks the calling thread until someThread terminates. Throws ThreadInterruptedException if the thread is interrupted while waiting. Bool someThread.join(millisecondsTimeout) Blocks the calling thread until a thread terminates or the specified time elapses Return true if the thread terminated, false if there was a timeout. Threads in C#

Priority property Property to get / set the priority of the thread Determines how much execution time the thread gets Public ThreadPriority { get; set; } Enum ThreadPriority {Lowest, BelowNormal, Normal, AboveNormal, Highest} Set the priority before you start the thread Threads in C#

Interrupting a thread Threads can be interrupted (by another thread) Even if the thread is sleeping or blocked for other reasons. Syntax: threadObj.Interrupt() Semantics In the interrupted class ThreadInterruptedException is thrown. Usage: Can be used to stop another thread Example: TryThread -> TryInterrupting Threads in C#

Exceptions in threads If a thread throws an exception the application terminates. The thread should catch its own exceptions. Trying to wrap the Start() in try … catch has no effects. It is not Start() that throws the exception Example: TryThread -> ThrowException Threads in C#

Foreground and background threads By default threads are foreground threads. As long as a foreground thread is alive, the application is alive. If only backgrounds threads are alive, the application finishes. When the application finished, all background threads are terminated immediately. Example someThreadObject.IsBackground = true; Threads in C#

Thread pooling New Thread(…) is expensive Making a new Thread object takes time + memory (app 1 MB stack) Thread pools recycle Thread objects Thread object which has finished executing, are put back into the pool They are not considered garbage. We will make fewer Thread objects, saving time + memory Threads run with by the pool are background threads They are terminated as soon as then application terminates In a simple program you can add Console.ReadLine() to the end of the program to keep the application alive. Threads in C#

Thread pooling, how to Task.Run(someMethod) is simpler than someMethod must have a signature Void someMethod() Creates a Task object and runs it in the background! Threads in C#

References and further readings Joe Albahari: Threading in C#, part 1 Getting Started http://www.albahari.com/threading/ John Sharp: Microsoft Visual C# 2012, Microsoft Press, 2012 Chapter 23 Improving Throughput by Using Tasks, page 541-584 Bart De Smet: C# 5.0 Unleashed, Sams 2013 Chapter 29 Threading and Synchronization, page 1443-1511 Mark Michaelis: Essential C# 5.0, Addison Wesley 2013 Chapter 18 Multithreading, page 727-808 Gaston Hillar: Professional Parallel Programming with C#, Wrox 2011 547 pages Threads in C#