Anda di halaman 1dari 17

Multithreading

Multitasking vs. Multithreading


Multitasking
It is the ability of an operating system to execute more than one
program simultaneously.
Individual programs are all isolated from each other in terms of
their memory and data.
Multithreading
Multithreading is the ability of an operating system to execute the
different parts of the program, called threads, simultaneously.
Thread shares memory and data with the other threads.

Hence, implementing multitasking is relatively easier in an operating


system than implementing multithreading.

Thread
A thread can be defined as a semi-process with a definite starting
point, an execution sequence and a terminating point.
It maintains its own stack where it keeps the exception handlers,
the scheduling priority and other details that the system might
need to re-activate that thread.
Why do we call it a semi-process!!!
That is because a full-blown process has its own memory area and
data, but the thread shares memory and data with the other
threads.
Process/Program, therefore, consists of many such threads each
running at the same time within the program and performing a
unique task.
Threads are also called lightweight processes that appear to run in
parallel with the main program. They are called lightweight
because they run within the context of the full-blown program
taking advantage of the resources allocated for the program.

Thread (Contd.)
Single Processor System
Threads can be run either in a preemptive mode or in a
cooperative mode.
The Preemptive Mode
The operating system distributes the processor time between the
threads and decides which thread should run next once the
currently active thread has completed its time-share on the
processor.
Hence the system interrupts the threads at regular intervals to
give chance to the next one waiting in the queue.
So no thread can monopolize the CPU at any given point of time.
The amount of time given to each thread to run depends on the
processor and the operating system.
what does switching mean??
It means that the processor stores the state of the outgoing
thread, restores the state of the incoming thread and then runs it.

Thread (Contd.)
Cooperative Mode
Each thread can control the CPU for as long as it needs it.
In this implementation, one thread can starve all the others for
processor time if it so chooses.
However, if a thread is not using the processor it can allow
another thread to use it temporarily.
Running threads can only give up control either if a thread calls a
yield function or if the thread does something that would cause it
to block, such as perform I/O.
Multi-processor system
The operating system can allocate individual threads to the
separate processors, which thus fastens the execution of the
program.
The efficiency of the threads also increases significantly because
the distribution of the threads on several processors is faster than
sharing time-slices on a single processor.

Thread (Contd.)
Are threads actually needed!!!
Scenario: Printing Pages
Disadvantages of Threads
If one program has many threads, then threads in the other
programs will naturally get less of the processor time.
A Large amount of processor time is consumed in controlling the
threads. The system also needs sufficient memory to store the
context information of each thread.
Hence, large number of threads is a blow to memory, bugging the
entire system and ultimately slowing the system down.

Multithreading
The ability of an operating system to execute different parts of a
program or threads simultaneously is termed multithreading.
System.Threading namespace
The System.Threading namespace provides classes and interfaces
that enable multithreaded programming.
The features of System.Threading namespace are as follows:
Describes the types of applications that can handle a collection of
threads.
Provides timer class to allow synchronized access to shared data.
Executes the threads within the CLR.
Create and destroys new threads from the existing thread.

Multithreading
Multithreading
Program 1

Thread A
Thread B

.
.
Program m

Thread C
Thread D

Mutithreading(Contd.)
Namespace System.Threading
{
Class Thread{}
Class Monitor{}
Class Mutex{}
Class ThreadPool{}
Class Timer{}
Public delegate void ThreadStart();
Enum ThreadState
{
Running,Stopped,Suspended.
Aborted,Background,WaitSleepJoin.
.
}
}

Multithreading(Contd.)
Using System.Threading
Class Example
{
Public void Longwork()
{
//Some algorithm taking a long time;
//we are going to launch it as a thread
}
Static void main()//runs as the main thread
{
Example example=new Example();
ThreadStart starter=new ThreadStart(example.Longwork);
Thread worker=new Thread(strater);
Worker.Start();//starts the concurrent thread
//(several threads can be launched)
// And continues it own work in parallel
}
}

Multithreading(Contd.)
Snippet of a program
Internal class EmployeeClass{
Public void Performjob(){
Console.WriteLine(emp therad
is{0},Thread.currentThread.GethashCode());
EmployeeClass ObjEmp=new EmployeeClass();
Thread bgThread=new Thread(new
ThreadStart(ObjEmp.Performjob));
bgThread.Start();
return 0;
}
}

Multithreading(Contd.)
Synchronization guarantees mutual exclusion (mutex) between
accessing threads.
Thread Synchronization
The features of thread synchronization are as follows:
Includes application resources that can be accessed from multiple
threads.
Prevents multiple threads from concurrent alteration.
Includes several classes and data types that can be used to
synchronize actions performed by two threads.
Uses the System.Threading.Interlocked class

Thread A

Process

Concurrent access

Thread B

Multithreading(Contd.)
Exploiting thread synchronization
A thread that requires to execute the same code needs to acquire the
same lock.
The thread is paused until the first thread releases the lock by calling
Moniter.exit(object).
Use the Monitor class to acquire a lock on an object by calling
Moniter.Enter(object).
Syntax:
System.Threading.Moniter.Enter(Expression);
Try{}
Finally
{
System.Threading.Moniter.Enter(Expression);
}

Thread Life Cycle


CREATED
Start()
RUNNING
LEAVING
MONITOR

LeaveMonitor()
Signaled by
Other Thread

Terminate()

DEAD

enterMonitor()
ENTERING
Other Thread Left
MONITOR
Monitor Signal
ENTERING
MONITOR

Condition()

waitCondition()
WAITING
CONDITION

SIGNALING
CONDITION

Mutex Class
Mutual exclusion (mutex) Class is used in concurrent programming to
avoid the concurrent use of unshareable resources.
The uses of mutex class are as follows:
Serializes the access to code, for example, a Monitor lock.
Creates named mutexes that can be used between processes.
Allows three types of constructors in C Sharp.
Mutex()
Mutex(bool initiallyOwened)
Mutex(bool initiallyOwened,string mutexName)

Mutex Class
Variable
Access
Lock

Thread A

Mutex Variable

Block

Thread B

THANK YOU

Anda mungkin juga menyukai