Chapter 3 (Threading)
Chapter 3 (Threading)
(Part 1)
Chapter 3
Outline
◼ Introduction
◼ What is a Thread?
◼ Threads vs Processes
❑ Process Model
❑ Thread Model
◼ Advantages of Multithreading
◼ Threading in C#
3
What is a Thread?
4
Threads vs Processes
5
Process Model
❑ A process is a sequential program in execution.
❑ Process components:
❑ The program (code) to be executed. Code Data
6
Thread Model
7
Why do we need threads?
Performance
Perceived
performance
Simplify coding
Multithreading
10
Example
13
Threads Concept
Multiple Thread 1
threads on
Thread 2
multiple
Thread 3
CPUs
Multiple Thread 1
threads
Thread 2
sharing a
Thread 3
single CPU
14
Advantages of Multithreading
15
Threading Namespace in C#
◼ Threading Namespace in C#
❑ System.Threading
namespace threadApp
{
public delegate void ThreadStart();
class Program
{
static void Work1(){
Console.WriteLine("Start");
}
static void Main(string[] args){
// Delegate instance
ThreadStart dt= new ThreadStart(Wordk1);
// Thread instance
Thread t1 = new Thread(dt.Invoke);
t1.Start();
Console.ReadKey();
}}}
19
Thread Life Cycle
◼ The life cycle of a thread starts when an object of the System.Threading class is created and
ends when the thread is terminated or completes execution.
◼ Following are the various states in the life cycle of a thread:
❑ The Unstarted State: It is the situation when the instance of the thread is created but the
cycle.
❑ The Not Runnable State: A thread is not executable, when:
❑ The Dead State: It is the situation when the thread completes execution or is aborted.
Thread lifecycle
Running Suspended
Unstarted Aborted
WaitSleepJoin
Example: without using threads using System;
using System.Threading;
namespace threadApp
{
class Program
{
static void Work1()
{
for(int i = 1; i <=10; i++)
{
Console.WriteLine("Work 1 is called " + i.ToString());
}
}
static void Work2()
{
for (int i = 1; i <= 10; i++)
{
Console.WriteLine("Work 2 is called " +
i.ToString());
}
}
Console.ReadKey();
}
}
}
Output
Example: with using threads using
using
using
System;
System.Collections.Generic;
System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace threadApp
{
class Program
{
static void Work1()
{
for(int i = 1; i <=10; i++)
{
Console.WriteLine("Work 1 is called " + i.ToString());
}
}
Console.ReadKey();
}
}
}
Output