Documente Academic
Documente Profesional
Documente Cultură
Chapter 4: Threads
Overview
Multithreading Models
Threading Issues
Pthreads
Windows XP Threads
Linux Threads
Java Threads
Operating System Concepts – 7th edition, Jan 23, 2005 4.2 Silberschatz, Galvin and Gagne ©2005
Threads
Operating System Concepts – 7th edition, Jan 23, 2005 4.3 Silberschatz, Galvin and Gagne ©2005
Single and Multithreaded Processes
Operating System Concepts – 7th edition, Jan 23, 2005 4.4 Silberschatz, Galvin and Gagne ©2005
Benefits
Responsiveness
Resource Sharing
Economy
Operating System Concepts – 7th edition, Jan 23, 2005 4.5 Silberschatz, Galvin and Gagne ©2005
User Threads
Operating System Concepts – 7th edition, Jan 23, 2005 4.6 Silberschatz, Galvin and Gagne ©2005
Kernel Threads
Examples
Windows XP/2000
Solaris
Linux
Tru64 UNIX
Mac OS X
Operating System Concepts – 7th edition, Jan 23, 2005 4.7 Silberschatz, Galvin and Gagne ©2005
Multithreading Models
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
Operating System Concepts – 7th edition, Jan 23, 2005 4.9 Silberschatz, Galvin and Gagne ©2005
Many-to-One Model
Operating System Concepts – 7th edition, Jan 23, 2005 4.10 Silberschatz, Galvin and Gagne ©2005
One-to-One
Operating System Concepts – 7th edition, Jan 23, 2005 4.11 Silberschatz, Galvin and Gagne ©2005
One-to-one Model
Operating System Concepts – 7th edition, Jan 23, 2005 4.12 Silberschatz, Galvin and Gagne ©2005
Many-to-Many Model
Operating System Concepts – 7th edition, Jan 23, 2005 4.13 Silberschatz, Galvin and Gagne ©2005
Many-to-Many Model
Operating System Concepts – 7th edition, Jan 23, 2005 4.14 Silberschatz, Galvin and Gagne ©2005
Two-level Model
Operating System Concepts – 7th edition, Jan 23, 2005 4.15 Silberschatz, Galvin and Gagne ©2005
Two-level Model
Operating System Concepts – 7th edition, Jan 23, 2005 4.16 Silberschatz, Galvin and Gagne ©2005
Thread Libraries
Operating System Concepts – 7th edition, Jan 23, 2005 4.17 Silberschatz, Galvin and Gagne ©2005
Thread Libraries
Operating System Concepts – 7th edition, Jan 23, 2005 4.18 Silberschatz, Galvin and Gagne ©2005
Multithreaded C program using Pthreads API
#include <pthread.h>
#include <stdio.h>
if (argc != 2) {
fprintf(stderr, “usage: a.out < integer value>\n”);
return -1;
}
if (atoi(argv[1]) < 0) {
fprintf(stderr, “%d must be >= 0\n”, atoi(argv[1]));
return -1;
}
Operating System Concepts – 7th edition, Jan 23, 2005 4.19 Silberschatz, Galvin and Gagne ©2005
Multithreaded C program using Pthreads API
/* get the default attributes */
pthread_attr_init(&attr);
/* create the thread */
pthread_create(&tid, &attr, runner, argv[1]);
/* wait for the thread to exit */
pthread_join(tid, NULL);
pthread_exit(0);
}
Operating System Concepts – 7th edition, Jan 23, 2005 4.20 Silberschatz, Galvin and Gagne ©2005
Multithreaded
#include <windows.h>
C program using the Win32 API
#include <stdio.h>
DWORD Sum; /* data is shared by the thread(s) */
/* the thread runs in this separate function */
DWORD WINAPI Summation(LPVOID Param)
{
DWORD Upper = *(DWORD*)Param;
for (DWORD i = 0; i <= Upper; i++)
Sum += i;
return 0;
}
Operating System Concepts – 7th edition, Jan 23, 2005 4.21 Silberschatz, Galvin and Gagne ©2005
Multithreaded C program using the Win32 API
// create the thread
ThreadHandle = CreateThread(
NULL, // default security attributes
0, // default stack size
Summation, // thread function
&Param, // parameter to thread function
0, // default creation flags
&ThreadId); // returns the thread identifier
if (ThreadHandle != NULL) {
// now wait for the thread to finish
WaitForSingleObject(ThreadHandle, INFINITE);
Operating System Concepts – 7th edition, Jan 23, 2005 4.22 Silberschatz, Galvin and Gagne ©2005
Java program for the summation example
class Sum {
private int sum;
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
}
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() {
int sum = 0;
for (int i = 0; i <= upper; i++)
sum += i;
sumValue.setSum(sum);
}
}System Concepts – 7th edition, Jan 23, 2005
Operating 4.23 Silberschatz, Galvin and Gagne ©2005
Java program for the summation example
Public class Driver
{
public static void main(String[] args) {
if (arg.length > 0) {
if (Integer.parseInt(args[0]) < 0)
System.err.println(args[0] + “ must be >= 0.”);
else {
// create the object to be shared
Sum sumObject = new Sum();
int upper = Integer.parseInt(args[0]);
Thread thrd = new Thread(new Summation(upper, sumObject));
thrd.start();
try {
thrd.join();
System.out.println
(“The sum of “+upper+” is “+sumObject.getSum());
} catch (InterruptedException ie) { }
}
}
else
System.err.println(“Usage: Summation < integer value>”);
}
Operating System Concepts – 7th edition, Jan 23, 2005 4.24 Silberschatz, Galvin and Gagne ©2005
}
Java
There are two techniques for creating threads in a Java program
Create a new class that is derived from the Thread class and to override
its run() method.
Define a class that implements the Runnable interface.
Operating System Concepts – 7th edition, Jan 23, 2005 4.25 Silberschatz, Galvin and Gagne ©2005
Sharing of Data
Operating System Concepts – 7th edition, Jan 23, 2005 4.26 Silberschatz, Galvin and Gagne ©2005
Threading Issues
Operating System Concepts – 7th edition, Jan 23, 2005 4.27 Silberschatz, Galvin and Gagne ©2005
Semantics of fork() and exec()
Operating System Concepts – 7th edition, Jan 23, 2005 4.28 Silberschatz, Galvin and Gagne ©2005
Thread Cancellation
Terminating a thread before it has finished
E.g. When a user presses the stop button on a web browser, all
threads loading the page are cancelled.
Two general approaches:
Asynchronous cancellation terminates the target thread
immediately.
Troublesome. The OS will reclaim system resources from a
canceled thread but will not reclaim all resources. So,
canceling may not free a system-wide resource
Deferred cancellation allows the target thread to periodically
check if it should be cancelled
Allows a thread to check whether it should be canceled at a
point when it can be canceled safely (“cancellation points” in
Pthreads).
Operating System Concepts – 7th edition, Jan 23, 2005 4.29 Silberschatz, Galvin and Gagne ©2005
Signal Handling
Signals are used in UNIX systems to notify a process that a particular
event has occurred. May be received synchronously or asynchronously.
A signal handler is used to process signals
1. Signal is generated by particular event
2. Signal is delivered to a process
3. Signal is handled
Options in multithreaded programs:
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.30 Silberschatz, Galvin and Gagne ©2005
Signal Handling
Synchronous signals are delivered to the same process that performed
the operation that caused the signal. Examples of synchronous signals
include illegal memory access, division by 0.
When a signal is generated by an event external to a running process,
that process receives the signal asynchronously (e.g. <control><C>).
Every signal may be handled by one of two possible handlers:
A default signal handler
A user-defined signal handler
When signal handling, some signals may simply be ignored, others may
be handled by terminating the program.
The standard UNIX function for delivering a signal is:
kill(aid_t aid, int signal)
Windows does not explicitly provide support for signals. They can be
emulated using asynchronous procedure calls (APCs) which allow a
user thread to specify a function that is to be called when the user
thread receives notification of a particular event.
Operating System Concepts – 7th edition, Jan 23, 2005 4.31 Silberschatz, Galvin and Gagne ©2005
Thread Pools
A multithreaded server has potential problems
The amount of time required to create the thread (together with the fact
that this thread will be discarded once finished)
If we allow all concurrent requests to be serviced in a new thread, we
have not placed a bound on the number of threads which may exhaust
system resources
Create a number of threads in a pool where they await work
Threads from the pool are awakened and when finished returned to pool.
Advantages:
Usually slightly faster to service a request with an existing thread than
create a new thread
Allows the number of threads in the application(s) to be bound to the size
of the pool
The number of threads in the pool
can be set heuristically based on factors such as the amount of memory
can be dynamically adjusted according to usage patterns
Consuming less memory with a small pool for low loads
Operating System Concepts – 7th edition, Jan 23, 2005 4.32 Silberschatz, Galvin and Gagne ©2005
Win32 Thread Pools
DWORD WINAPI PoolFunction(AVOID Param) {
/* This function runs as a separate thread */
}
A pointer to PoolFunction() is passed to one of the functions in the
thread pool API, and a thread from the pool executes this function. One
such member in the thread pool API is the QueueUserWorkItem
which has three parameters
LPTHREAD_START_ROUTINE Function – a pointer to the function
that is to run as a separate thread
PVOID Param – the parameter passed to Function
ULONG Flags – flags indicating how the thread pool is to create and
manage execution of the thread.
An example call
QueueUserWorkItem(&PoolFunction, NULL, 0);
Which causes a thread from the thread pool to invoke PoolFunction()
on behalf of the programmer.
Operating System Concepts – 7th edition, Jan 23, 2005 4.33 Silberschatz, Galvin and Gagne ©2005
Thread Specific Data
Operating System Concepts – 7th edition, Jan 23, 2005 4.34 Silberschatz, Galvin and Gagne ©2005
Scheduler Activations
Operating System Concepts – 7th edition, Jan 23, 2005 4.35 Silberschatz, Galvin and Gagne ©2005
Scheduler Activations
Operating System Concepts – 7th edition, Jan 23, 2005 4.36 Silberschatz, Galvin and Gagne ©2005
Pthreads
Operating System Concepts – 7th edition, Jan 23, 2005 4.37 Silberschatz, Galvin and Gagne ©2005
Windows XP Threads
Win32 API
Implements the one-to-one mapping
Each thread contains
A thread id
Register set
Separate user and kernel stacks
Private data storage area for run-time libraries and DLLs.
The register set, stacks, and private storage area are known as the context of
the threads
The primary data structures of a thread include:
ETHREAD (executive thread block)
Contains thread start adress, pointer to parent process, pointer to KTHREAD
KTHREAD (kernel thread block)
Contains scheduling and synchronization info, kernel stack, pointer to TEB
TEB (thread environment block)
Contains thread identifier, user stack, thread-local storage (thread specific data)
Operating System Concepts – 7th edition, Jan 23, 2005 4.38 Silberschatz, Galvin and Gagne ©2005
Linux Threads
Linux refers to them as tasks rather than threads
Thread creation is done through clone() system call
clone() allows a child task to share the address space of the parent
task (process)
File-system info may be shared
The same memory space may be shared
Signal handlers may be shared
The set of open files may be shared
Rather then copying all data structures, the new task points to
the data structures of the parent task
A unique kernel data structure (struct task_struct) exist for
each task in the system. It contains pointers to other data structures
where these data are stored
When fork() is invoked, a new task is created, along with a copy of
all the associated data structures of the parent process
Operating System Concepts – 7th edition, Jan 23, 2005 4.39 Silberschatz, Galvin and Gagne ©2005
Java Threads
Operating System Concepts – 7th edition, Jan 23, 2005 4.40 Silberschatz, Galvin and Gagne ©2005
Java Thread States
Operating System Concepts – 7th edition, Jan 23, 2005 4.41 Silberschatz, Galvin and Gagne ©2005
End of Chapter 4