You are on page 1of 11

5.

Threads
Thread : A thread, sometimes we can called a Lightweight Process ( LWP ), is a
basic unit of CPU utilization. It comprises thread ID, a program counter, a register set
and a stack.
“ A Thread is a line of execution. It is the smallest unit of code that is
dispatched by the scheduler. Thus a process can contain multiple threads to execute its
different sections. This is called Multithreading “.
It shares with a others threads belonging to the same process its code section,
data section and other operating system resources such as open files and signals.
A traditional or heavy weight process has a single thread of control. If the
process has multiple threads of control, it can do more than one task at a time.
Single and Multithreaded Processes
:

Benefits of threads :
The benefits of multithreaded programming can be broken down to four major
categories.
i) Responsiveness
ii) Resource Sharing
iii) Economy
iv) Utilization of MP Architectures

Page 1
i) Responsiveness : Multithreading is an interactive application may allow a program
to continue running even if part of it is blocked or is performing a lengthy operation,
there by increasing the responsiveness to the user.
ii) Resource Sharing : By default, threads share the memory and the resources of the
process to which they belong. The benefit of code sharing is that it allows an
application to have several different threads of activity all within the same address
space.
iii) Economy : Threads share the resources of the processes to which they belong. It
is more economical to create and context switch threads. In Solaris2, creating a
process is about 30 times slower than is creating a thread and context switch is about
5 times slower.
iv) Utilization of Multiprocessor architecture : A single thread process can only run
on one CPU. Multithreading on a multi-CPU machine increases concurrency i.e.,
threads are distributed to various processors and execution speed will be increased.
Levels of Threads :
There two types of levels of threads. They are User Level and Kernel threads.
i) User Threads : These are supported above the kernel and are implemented by a
thread library at user level. The library provides support for thread creation,
scheduling and management with no support from the kernel.
User threads includes POSIX Pthreads, Mach C-threads and Solaris2 UI-
threads.
ii) Kernel Threads : These are supported directly by the operating system. The
kernel provides thread creation, scheduling and management in kernel space. Because
thread management done by the operating system. Kernel threads generally slower to
create and manage than user threads.
Examples:
i) Windows XP/2000
ii) Solaris
iii) Linux
iv) Tru64 UNIX
v) Mac OS X

Page 2
Multithreading Models :
Many systems provide support for both user and kernel threads. There are
three common types of multi threading. They are
i) Many-to-One
ii) One-to-One
iii) Many-to-Many

i) Many-to-One Model :
This model maps many user level threads to one kernel thread. Thread
management is done in user space. So, it is efficient, but the entire process will block
if a thread makes a blocking system call. Multiple threads are unable to run in parallel
on multiprocessors but single thread can access the kernel at a time. Green threads – a
thread library available for Solaris 2 – uses this model.

ii) One-to One Model :


The one-to-one model maps each user thread to a kernel thread. It provides
more concurrency than the many-to-one model by allowing another thread to run
when a thread makes a system blocking call. It also allows multiple threads to run in
parallel on multiprocessors. The only drawback of this model is that creating a user
thread requires creating the corresponding kernel thread.
Examples :
i) Windows NT/XP/2000
ii) Linux

Page 3
iii) Solaris 9 and later

iii) Many-to-Many Model :


This model multiplexes many user level threads to a smaller or equal number
of kernel threads. The number of kernel threads may be specific to either a particular
application or a particular machine. This model allows the developer to create as
many user threads.
Ex: Windows NT/2000 with the Thread Fiber package

Threading Issues
:
a) Semantics of fork() and exec() system calls
b) Thread cancellation
c) Signal handling
d) Thread pools
e) Thread specific data
f) Scheduler activations

Page 4
Semantics of fork() and exec() system calls :
Some UNIX systems have chosen to have two versions of fork, one that
duplicates all threads and another duplicates only the thread that invoked the fork
system call.
If exec is called immediately after forking, then duplicating all threads is
unnecessary, as the program specified in the parameters to exec will replace the
process.
Thread cancellation :
Thread cancellation is the task of terminating a thread before it has completed.
There are two general approaches for cancellation of thread :
i) Asynchronous cancellation terminates the target thread
immediately
ii) Deferred cancellation allows the target thread to periodically check
if it should be cancelled.

Signal Handling :
A signal is used in UNIX systems to notify a process that
a particular event has occurred. A signal may be received either synchronously or
asynchronously, depending up on source and reason for the event being signaled.
Whether a signal is synchronous or asynchronous, all signals follow the same
pattern :
1. Signal is generated by particular event
2. Signal is delivered to a process
3. Signal is handled

Every signal may be handled by one of two possible handlers :


1. A default signal handler
2. A user defined signal handler
In general, the following options exist :
1. Deliver the signal to the thread to which the signal applies
2. Deliver the signal to every thread in the process
3. Deliver the signal to certain threads in the process
4.Assign a specific thread to receive all signals for the process

Page 5
Thread Pools :
The general idea behind a thread pool is to create a number of threads at
process startup and place them into a pool, where they sit and wait for work.
The benefits of thread pools are :
1)Usually slightly faster to service a request with an existing thread
than create a new thread
2)Allows the number of threads in the application(s) to be bound to the
size of the pool
Thread-Specific data :
Each thread might need its own copy of certain data in some circumstances.
We call such data as Thread-Specific data.

Pthreads :
Pthreads refers to the POSIX standard ( IEEE 1003.1c ) defining an API for
thread creation and synchronization. This is a specification for thread behavior, not an
implementation.

Solaries 2 Threads :

Solaris 2 supports user-level threads with a library containing APIs for thread
creation and management. Solaris 2 defines an intermediate level of threads as well.
Between user level threads and kernel level threads light weight processes ( LWP ).

Page 6
Each process contains at least one LWP. The thread library multiplexes user level
threads on the pool of LWPs for the process and only user level threads are currently
connected to an LWP accomplish work. The rest are either blocked or waiting for an
LWP on which they can run.
User-level threads may be either bound and unbound. A bound user level
thread is permanently attached to a LWP. Only that thread runs on the LWP and by
request the LWP can be dedicated to a single processor ( the rightmost thread in the
above figure ).
An unbound thread is not permanently attached to any LWP. All unbound
threads in an application are multiplexed onto the pool of available LWPs for the
application. Threads are unbound by default.
The developers used the following data structures to implement threads on
Solaris 2 :
a) A user level thread contains a thread ID, register set ( including a PC
and stack pointer ), stack and priority (used by the thread library for scheduling
purpose). None of these data structures are kernel resources; all exist within user
space.
b) An LWP has a register set for the user level thread it is running, as
well as memory and accounting information. A LWP is a kernel data structure and it
resides in kernel space.
c) A kernel thread has only a small data structure and a stack. The data
structure includes a copy of the kernel registers, a pointer to the LWP to which is
attached and priority and scheduling information.

Page 7
A Solaris 2 process contains a process ID ( PID ), memory map, list of files
open, priority and a pointer to a list of LWPs associated with the process is shown in
the above figure.

Java Threads :
In Java, thread are provided either by the operating system or threads package.
Thread Creation :
Java threads may be created by:
a) Extending Thread class
b) Implementing the Runnable interface
Java threads are managed by the JVM ( Java Virtual Machine ). The following
methods are required to create a thread.
The method start( ) that actually creates the new thread. Calling the
start( ) method for the new object
a) allocates memory and initializes a new thread in the JVM
b) calls the run( ) method making the thread eligible to be run
by the JVM.
When the program runs, two threads are created by the JVM. The first is the
thread associated with the application – the thread that starts execution at the main( )
method. The second thread is the runner thread that is created explicitly with the
start( ) method. The runner thread begins execution in its run( ) method.

Thread Management :
Java provides several APIs ( Application Programming Interface ) for
managing threads, including :
a) suspend( ) : Suspends execution of the currently running thread.
b) sleep( ) : Puts the currently running thread to sleep for a specified amount

Page 8
of time.
c) resume( ) : Resumes execution of a thread that had been suspended.
d) stop( ) : Stops execution of a thread. Once a thread has been stopped, it
can’t be resumed or started.
Thread States :
A Java thread can be in one of four possible states :
a)New : When an object for the thread is created, is in the ‘New’ state.
b)Runnable : When a thread invokes run( ) method, it is in the
Runnable state. A thread is in the Runnable state is
eligible to run by the JVM.
c)Blocked : A thread becomes Blocked, if it performs a blocking
statement such as by doing I/O or if it invokes certain Java
thread methods such as sleep( ) or suspend( ).
d)Dead : A thread moves to the dead state when its run( ) method
terminates or when its stop( ) method is called.

Thread creation using Runnable :


The Runnable is an interface and is defined as
public interface Runnable
{
public abstract void run( );
}
Now we have to define a class which implements Runnable interface.
class A implements Runnable
{
public void run ( )
{
System.out.println(“I am working with Runnable”);
}
}
Page 9
Now we have to define the main( ) method class as the following :
public class R_test
{
public static void main ( String args [ ] )
{
Runnable r = new A( );
Thread t = new Thread( r );
t.start( );
System.out.println( “ I am in main thread” );
}

Thread Creation using Thread class :


The Thread class also we can create a thread in Java as the following :
class A extends Thread
{
public void run( )
{
System.out.println(“I am in Thread A”);
}
}
Now we have to define the main( ) method class.
public class T_test
{
Public static void main( String args [ ] )
{
A aa = new A ( );
aa.start( );
System.out.println(“I am in Main”);
}
}
Using the above code, two threads will be created i.e., main and A thread.
Except main thread, the remaining threads code must be written in the run( ) method.
In the similar manner, we can create any number of threads by defining the separate
class extending Thread class with run( ) method.
Page 10
If we run the multithreaded programs, we don’t expect the sequence of
outputs.

*********** End of Chapter : 5 *************

Page 11

You might also like