0% found this document useful (0 votes)
14 views26 pages

Chapter 3 (Threading)

Uploaded by

633611sse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views26 pages

Chapter 3 (Threading)

Uploaded by

633611sse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Working with Threads in C#

(Part 1)

Chapter 3
Outline
◼ Introduction
◼ What is a Thread?

◼ Threads vs Processes
❑ Process Model
❑ Thread Model

◼ Why do we need threads?


◼ Multithreading

◼ Advantages of Multithreading

◼ Threading in C#

◼ Thread Life Cycle


Introduction

◼ Performing operations concurrently (in parallel)


❑ We can walk, talk, breathe, see, hear, smell... all at the
same time
❑ With threads Computers can do this as well - download
a file, print a file, receive email, run the clock, more or
less in parallel….

3
What is a Thread?

◼ Thread: is the fundamental unit of execution.


◼ Thread allows the program to run tasks in parallel
◼ Thread may be managed by the operating system or by a
user application
◼ More than one thread can be executing code inside the same
process (application).

4
Threads vs Processes

◼ What’s the difference between a process and a thread?


❑ Processes run in parallel on a computer, while threads run in
parallel within a single process.
❑ Processes have their own memory space, whereas threads
share memory.
❑ Processes are fully isolated from each other; while threads have
just a limited degree of isolation.
❑ Hence processes are “heavyweight” while threads are
“lightweight”

5
Process Model
❑ A process is a sequential program in execution.
❑ Process components:
❑ The program (code) to be executed. Code Data

❑ The data on which the program will execute. Process Status


Resource

❑ Resources required by the program.


❑ The status of the process execution.
❑ A process runs in an abstract machine Abstract Machine Environment
environment (could be OS) that manages the
sharing and isolation of resources among the
community of processes.

6
Thread Model

❑ In the thread model:


❑ Each thread is associated with a process.
❑ A thread is an entity that executes by relying on the
code and resources, holding by the associated
Resource
process.
❑ Several threads could be associated with a single Process Thread
process. Those threads share the code and resources Data Code Data
of the process. Process Status Thread Status
❑ A thread allocates part of the process’s resources for
its needs.
❑ A thread has its own data and status.

7
Why do we need threads?

◼ To enhance parallel processing


◼ To increase response to the user
◼ To utilize the idle time of the CPU
◼ Prioritize your work depending on priority
Why should we use threads?

Performance

Perceived
performance

Simplify coding
Multithreading

◼ The process of executing multiple threads simultaneously is


known as multithreading.
◼ The main purpose of multithreading is to provide simultaneous
execution of two or more parts of a program to maximum
utilize the CPU time.
◼ A multithreaded program contains two or more parts that can
run concurrently. Each such part of a program called thread.

10
Example

◼ Consider a simple web server


❑ The web server listens for request and serves it
❑ If the web server was not multithreaded, the requests
processing would be in a queue, thus increasing the response
time and also might hang the server if there was a bad request.
❑ By implementing in a multithreaded environment, the web
server can serve multiple request simultaneously thus
improving response time
Multitasking vs Multithreading vs Multiprocessing vs parallel
processing
◼ Multitasking: Ability to execute more than one task at the same time is
known as multitasking.
◼ Multithreading: It is a process of executing multiple threads
simultaneously. Multithreading is also known as Thread-based
Multitasking.
◼ Multiprocessing: It is same as multitasking, however in multiprocessing
more than one CPUs are involved. On the other hand one CPU is
involved in multitasking.
◼ Parallel Processing: It refers to the utilization of multiple CPUs in a
single computer system.
12
An example of multithread

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

◼ More responsive to user input – GUI application can interrupt


a time-consuming task.
◼ Server can handle multiple clients concurrently
◼ Can take advantage of parallel processing.

15
Threading Namespace in C#

◼ Threading Namespace in C#

❑ System.Threading

◼ Consists of classes for synchronizing thread activities.


Thread Class

◼ In C#, Threads are managed by the:


System.Threading.Thread class.
❑ C# threads are passed a static or instance function of some C# class
using a standard delegate of type “ThreadStart”.
Starting C# Threads
1) Creates a thread object
❑ Thread thread = new Thread(new ThreadStart(ThreadFunc));
◼ ThreadStart delegate identifies the method that the thread executes when it starts.
◼ ThreadFunc can be: Static or instance member of the class instance that created the thread

2) starts the thread


◼ thread.Start();
Example using System;
using 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

Start method is not called.


❑ The Ready State: It is the situation when the thread is ready to run and waiting CPU

cycle.
❑ The Not Runnable State: A thread is not executable, when:

◼ Sleep method has been called

◼ Wait method has been called

◼ Blocked by I/O operations

❑ 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());
}
}

static void Main(string[] args)


{
Work1();
Work2();

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());
}
}

static void Work2()


{
for (int i = 1; i <= 10; i++)
{
Console.WriteLine("Work 2 is called " + i.ToString());
}
}

static void Main(string[] args)


{
Thread t1 = new Thread(Work1);
Thread t2 = new Thread(Work2);
t1.Start();
t2.Start();

Console.ReadKey();
}
}
}
Output

You might also like