Download Threads

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Chapter 4
Threads
Chapter 4: Threads
 Overview
 Multithreading Models
 Thread Libraries

POSIX Threads

Win32 Threads

Java Threads
 Threading Issues
Operating System Concepts – 7th edition, Jan 23, 2005
4.2
Silberschatz, Galvin and Gagne ©2005
4.1 Overview
Threads

A thread is a basic unit of CPU utilization

A heavy-weight process has a single thread of execution

A multi-threaded process has multiple threads of execution



Each thread is sometimes called a light-weight process
A thread consists of

Thread ID

Program counter

Register set

Stack
It shares the following with other threads of the same process

Code section

Data section

Open files

Signals
Operating System Concepts – 7th edition, Jan 23, 2005
4.4
Silberschatz, Galvin and Gagne ©2005
Single and Multithreaded Processes
signals
signals
PC
PC
Operating System Concepts – 7th edition, Jan 23, 2005
4.5
PC
PC
Silberschatz, Galvin and Gagne ©2005
Benefits of Multi-threaded Programming

Responsiveness


Resource sharing



May allow a program to continue running even if part of it is blocked or
is performing a lengthy operation
Allows an application to have several different threads of activity within
the same address space
Economy

More economical to context-switch between threads than between
processes

In Solaris, it takes 30 times longer to create a new process and five
times longer to context switch to a process as compared to threads
Utilization of multiprocessor architectures

May allow threads to run in parallel on different processors
Operating System Concepts – 7th edition, Jan 23, 2005
4.6
Silberschatz, Galvin and Gagne ©2005
4.2 Multithreading Models
User Threads and Kernel Threads
 Support for threads are provided either

At the user level for user threads
 At the kernel level for kernel threads
 User threads are supported above the kernel and are managed
without kernel support
 Kernel threads are supported and managed directly by the
operating system
 Virtually all contemporary operating systems support kernel
threads
 Multithreading models consist of
 Many-to-One

One-to-One
 Many-to-Many
Operating System Concepts – 7th edition, Jan 23, 2005
4.8
Silberschatz, Galvin and Gagne ©2005
Many-to-One Model
 Many user-level threads are
mapped to a single kernel
thread
 Examples:

Solaris Green Threads

GNU Portable Threads
Operating System Concepts – 7th edition, Jan 23, 2005
4.9
Silberschatz, Galvin and Gagne ©2005
One-to-One Model
 Each user-level thread is mapped to a kernel thread
 Examples

Windows NT/XP/2000

Linux

Solaris 9 and later
Operating System Concepts – 7th edition, Jan 23, 2005
4.10
Silberschatz, Galvin and Gagne ©2005
Many-to-Many Model
 Allows many user level
threads to be mapped
to many kernel threads
 Allows the operating
system to create a
sufficient number of
kernel threads
 Solaris prior to version 9
 Windows NT/2000 with
the ThreadFiber
package
Operating System Concepts – 7th edition, Jan 23, 2005
4.11
Silberschatz, Galvin and Gagne ©2005
4.3 Thread Libraries
Thread Libraries
 A thread library provides an API for creating and managing threads
 Two primary ways of implementing a thread library

Provide a library entirely in user space with no kernel support


Invoking a function in the library results in a local function
call in user space
Provide a kernel-level library supported directly by the
operating system

Invoking a function in the library results in a system call to
the kernel
Operating System Concepts – 7th edition, Jan 23, 2005
4.13
Silberschatz, Galvin and Gagne ©2005
Thread Library Implementations
 POSIX Pthreads

May be provided as either a user- or kernel-level library
 Win32 API

Provided as a kernel-level library
 Java API

Threads are the fundamental model of program execution in a Java
program

Thread creation and management is a central part of the Java API

In the Java Virtual Machine, a Java program starts out as a single
thread created by the JVM

Java threads are typically implemented using the thread library that
is available on the host system (Win32 API on Windows; Pthreads
on UNIX)
Operating System Concepts – 7th edition, Jan 23, 2005
4.14
Silberschatz, Galvin and Gagne ©2005
POSIX Pthreads Example
#include <pthread.h>
#include <stdio.h>
int sum; /* this data is shared by the thread(s) */
void *runner(void *parameters); /* the thread */
int main(int argc, char *argv[])
{
pthread_t threadID; /* the thread identifier */
pthread_attr_t attributes; /* set of attributes for the thread */
/* get the default attributes */
pthread_attr_init(&attributes);
/* create the thread */
pthread_create(&threadID, &attributes, runner, argv[1]);
/* now wait for the thread to exit */
pthread_join(threadID, NULL);
printf("sum = %d\n", sum);
} // End main
Operating System Concepts – 7th edition, Jan 23, 2005
4.15
Silberschatz, Galvin and Gagne ©2005
POSIX Pthreads Example (continued)
// The thread will begin control in this function
void *runner(void *parameters)
{
int i;
int upper;
upper = atoi(parameters);
sum = 0;
if (upper > 0)
{
for (i = 1; i <= upper; i++)
sum = sum + i;
}
pthread_exit(0);
} // End runner
Operating System Concepts – 7th edition, Jan 23, 2005
4.16
Silberschatz, Galvin and Gagne ©2005
Win32 Threads Example
#include <windows.h>
#include <stdio.h>
DWORD Sum; /* data that is shared by the thread(s) */
DWORD WINAPI Summation(LPVOID Parameters);
int main(int argc, char *argv[])
{
DWORD ThreadId;
HANDLE ThreadHandle;
int CommandParameters = atoi(argv[1]);
// create the thread
ThreadHandle = CreateThread(NULL, 0, Summation,
&CommandParameters, 0, &ThreadId);
if (ThreadHandle == NULL)
return –1;
WaitForSingleObject(ThreadHandle, INFINITE);
CloseHandle(ThreadHandle);
printf("sum = %d\n", Sum);
} // End main
Operating System Concepts – 7th edition, Jan 23, 2005
4.17
Silberschatz, Galvin and Gagne ©2005
Win32 Threads Example (continued)
// The thread runs in this separate function
DWORD WINAPI Summation(PVOID Parameters)
{
DWORD Upper = *(DWORD *)Parameters;
for (DWORD i = 0; i <= Upper; i++)
Sum = Sum + i; // Update of global variable
return 0;
} // End Summation
Operating System Concepts – 7th edition, Jan 23, 2005
4.18
Silberschatz, Galvin and Gagne ©2005
Java Threads Example
class Sum
{
private int sum;
public int get()
{
return sum;
}
public void set(int sum)
{
this.sum = sum;
}
} // End class
Operating System Concepts – 7th edition, Jan 23, 2005
4.19
Silberschatz, Galvin and Gagne ©2005
Java Threads Example (continued)
class Summation implements Runnable
{
private int upper;
private Sum sumValue;
public Summation(int upper, Sum sumValue)
{
this.upper = upper;
this.sumValue = sumValue;
}
public void run() // Mandatory method
{
int sum = 0;
for (int i = 0; i <= upper; i++)
sum = sum + i;
sumValue.set(sum);
}
} // End class
Operating System Concepts – 7th edition, Jan 23, 2005
4.20
Silberschatz, Galvin and Gagne ©2005
Java Threads Example (continued)
public
{
public
{
Sum
int
class Driver
static void main(String[] args)
sumObject = new Sum();
upper = Integer.parseInt(args[0]);
Thread worker = new Thread(new Summation(upper, sumObject));
worker.start();
try
{
worker.join();
}
catch (InterruptedException ie)
{ }
System.out.println("The sum of " + upper + " is " +
sumObject.get());
} // End main
} // End class
Operating System Concepts – 7th edition, Jan 23, 2005
4.21
Silberschatz, Galvin and Gagne ©2005
4.4 Threading Issues
Issues Concerning Multithreaded
Programs
 Semantics of fork() and exec() system calls
 Thread cancellation
 Signal handling
 Thread pools
 Thread-specific data
Operating System Concepts – 7th edition, Jan 23, 2005
4.23
Silberschatz, Galvin and Gagne ©2005
Semantics of fork() and exec()
 The semantics of the fork() and exec() system calls change in
a multithreaded program
 If one thread in a program calls fork(), does the new process
duplicate all threads, or is the new process single-threaded?
 Some UNIX systems have two versions of fork() to handle both
situations
 The exec() family of system calls works the same way as
described for a process

When a thread invokes an exec()function, the program
specified in the function call will replace the entire process –
including all threads
Operating System Concepts – 7th edition, Jan 23, 2005
4.24
Silberschatz, Galvin and Gagne ©2005
Thread Cancellation


Thread cancellation means to terminate a target thread (from outside of the
thread) before it has normally completed

Example #1: Multiple threads are searching a database. One thread
returns the result and the other threads are terminated

Example #2: Multiple threads are loading information in a single web
page. The browser stop button is pressed and all threads loading the
page are cancelled
Two general approaches to thread cancellation

Asynchronous cancellation


Deferred cancellation


One thread immediately terminates the target thread
The target thread periodically checks whether it should terminate,
allowing it an opportunity to terminate itself in an orderly fashion
Difficulties occur in situations where

Resources have been allocated to a cancelled thread

A thread is canceled while in the midst of updating data that it is sharing
with other threads
Operating System Concepts – 7th edition, Jan 23, 2005
4.25
Silberschatz, Galvin and Gagne ©2005
Signal Handling

A signal is used in UNIX to notify a process that a particular event has occurred

A signal may be received either synchronously or asynchronously


Depends on the source of and reason for the event being signaled
All signals follow the same pattern
1.
A signal is generated by the occurrence of a particular event
2.
A generated signal is delivered to a process
3.
Once delivered, the signal must be handled

Examples: illegal memory access, divide by zero, control-C, expired timer

In a multithreaded program, which thread gets delivered the signal?

Deliver the signal to the thread to which the signal applies

Deliver the signal to every thread in the process

Deliver the signal to certain threads in the process

Assign a specific thread to receive all signals for the process
Operating System Concepts – 7th edition, Jan 23, 2005
4.26
Silberschatz, Galvin and Gagne ©2005
Thread Pools

An unlimited number of concurrently active threads could exhaust
system resources, such as CPU time or memory

One solution to this issue is a thread pool


Create a number of threads at process startup and place them in
a pool, where they sit and wait for work

When a server receives a request, it awakens a thread from this
pool (if one is available) and passes it the request to service

Once the thread completes its service, it returns to the pool and
awaits more work

If the pool contains no available thread, the server waits until one
becomes free
Benefits

Servicing a request with an existing thread is usually faster than
waiting to create a thread

A thread pool will limit the number of threads that exist at any one
point in time

This is particularly important on systems that cannot support
a large number of concurrent threads
Operating System Concepts – 7th edition, Jan 23, 2005
4.27
Silberschatz, Galvin and Gagne ©2005
Thread-Specific Data
 Threads belonging to a process share the data of the process
 However, each thread might need its own copy of certain data,
referred to as thread-specific data
 For example, each transaction in a transaction processing
system may be handled by a separate thread
 This feature is supplied by the three major APIs
Operating System Concepts – 7th edition, Jan 23, 2005
4.28
Silberschatz, Galvin and Gagne ©2005
End of Chapter 4