Chapter 4: Threads

buninnateΛογισμικό & κατασκευή λογ/κού

18 Νοε 2013 (πριν από 3 χρόνια και 4 μήνες)

125 εμφανίσεις

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition,

Chapter 4: Threads

4.
2

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Chapter 4: Threads


Thread:


A basic unit of CPU utilization


Consists of
a thread ID, a program counter, a register set, and a stack


Shares

with other threads of the same process its
code section, data section,
and other OS resources (open files and signal)



Single
-
threaded Process:


A process that has only a single thread of control


A traditional process is single
-
threaded, called a heavyweight process



Multithreaded Process:


A process that has only multiple threads of control


Can perform more tan one task at a time.


4.
3

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Single and Multithreaded Processes

Shared by all threads

4.
4

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Benefits


Responsiveness


Multithreading allows a program to continue even if part of it is blocked


or is performing lengthy operations


Example: a web browser


one thread for user interaction,


another thread for image download


Resource Sharing


Processes

may only share resources thru techniques such as shared memory


and message passing, which are
explicitly arranged by programmer
.


Threads

share memory and the resources of the process they belong
by default


Economy


Allocating memory and resources for process creation is costly


Creating and context
-
switching threads is more economical


Scalability


Threads may be running in parallel in a multiprocessor architecture.


A single
-
threaded process can only run on one processor,


no matter how many processors are available.


4.
5

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Multithreaded Server Architecture

Support for threads may be provided either at the user level (
for
user threads
), or by the kernel (for
kernel threads
)

4.
6

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

User Threads


Supported above the kernel



Managed by user
-
level thread library, without kernel support



Three primary thread libraries:



POSIX
Pthreads




Win32 threads




Java threads

4.
7

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Kernel Threads


Supported by the Kernel



Each kernel thread is individually scheduled by the kernel,


sometimes called a light
-
weight process



Virtually all contemporary OS support kernel threads



Examples


Windows XP/2000


Solaris


Linux


Tru64 UNIX


Mac OS X

4.
8

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Multithreading Models


Many
-
to
-
One



One
-
to
-
One



Many
-
to
-
Many


4.
9

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Many
-
to
-
One


Many user
-
level threads mapped to single kernel
thread



Examples:



Solaris Green Threads



GNU Portable Threads




The entire process blocks if a thread makes a blocking system
call because the kernel sees only one thread from this process.


Only one thread can access the kernel at a time. Multiple threads
are unable to run in parallel on multiprocessors

4.
10

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

One
-
to
-
One


Each user
-
level thread maps to kernel thread



Examples


Windows NT/XP/2000


Linux


Solaris 9 and later



Allows another thread to run if a thread makes a blocking system
call.


Allows multiple threads to run in parallel on multiprocessors


Drawback
: creating a user thread requires creating a kernel thread


潶敲桥hd

慦晥捴c 灥牦潲p慮ae


4.
11

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Many
-
to
-
Many Model


Allows
many

user level threads to be mapped to
a smaller or
equal number

of 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

4.
12

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Two
-
level Model


Similar to M:M
,
except that it allows a user thread
to be bound to kernel thread



Examples


IRIX


HP
-
UX


Tru64 UNIX


Solaris 8 and earlier

4.
13

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Thread Libraries


Thread library provides programmer with API

for creating and
managing threads


Two primary ways of implementing a thread library

(code and data
structures)

1.
To provide a
user
-
level library

entirely in user space

with
no
kernel support


Invoking a function in the API



a local function call in the user space

2.
To implement a
kernel
-
level library

directly supported by
the OS


Invoking a function in the API




a system call to the kernel.

4.
14

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Pthreads


A POSIX standard

(IEEE 1003.1c)
API

for thread creation
and synchronization ( a specification)



API
only specifies behavior of the thread library
,
implementation is up to development of the library



Common in UNIX
operating systems (Solaris, Linux, Mac
OS X)


4.
15

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Pthreads Example (sum.c)

(1+2+…+N)

#include <pthread.h>

#include <stdio.h>

#include <sys/types.h>


int
sum

= 0;
/*
this data is shared by the thread(s)
*/

void *runner(void *param);
/* the thread */


int main(int argc, char *argv[])
{


pthread_t

tid; /* the thread identifier */


pthread_attr_t

attr; /* set of thread attributes */


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;


}





/* get the default attributes */


pthread_attr_init
(&attr);


/* create the thread */



pthread_create
(&tid,&attr,
runner
,
argv[1]
);


/* now wait for the thread to exit */


pthread_join
(tid,NULL);


printf("Sum = %d
\
n",
sum
);

}



// The thread will begin control in this function

void *runner (void *param) {


int i, upper = atoi (param);


sum

= 0;


for (i=1; i<=upper; i++){


sum
+= i;


}


pthread_exit(0);

}


To compile : % gcc

lpthread sum.c

To run : % ./a.out 5

Output : % Sum =
15

4.
16

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Java Threads


Java threads

are
managed by the JVM



Typically
implemented using the threads model provided
by underlying OS



Java threads

may be
created by:



Extending
Thread class


Implementing the
Runnable interface


4.
17

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Java Threads
-

Example Program

1. class MutableInteger

2. class Summation implements Runnable

3. public class Driver

constructor

instance variables

value: an instance variable

getValue(): an instance method

4.
18

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Java Threads
-

Example Program

A memory address
is passed

an integer
is passed

4.
19

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Java Thread States

4.
20

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Java Threads
-

Producer
-
Consumer

public interface
Channel
{


public abstract void
send
(Object item);


public abstract Object
receive

();

}

import java.util.Vector;


public class
MessageQueue

implements
Channel
{


private Vector queue;



public MessageQueue(){


queue = new Vector();


}


public void
send
(Object item){


queue.addElement(item);


}


public Object
receive
(){


if (queue.size() == 0){


return null;


}


else{


return queue.remove(0);


}


}

}

A MessageQueue is a Channel.

It serves as a mailbox.

This implements a nonblocking send

This implements a nonblocking receive

addElement(.) and remove(.)
are synchronized methods

4.
21

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Java Threads
-

Producer
-
Consumer

The memory address of mailBox is passed to
both Producer and Consumer constructors




mailBox is accessible by both threads

See pp.123
-
124, OS Concepts with Java, 6
th

Ed.

for interface Channel and class MessageQueue

Channel contains two abstract methods: send() and receive()

MessageQueue is a class that implements send() and receive()

4.
22

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Java Threads
-

Producer
-
Consumer

Sleep for a while

Provide your own code

Send message to mbox, which then adds the
message to a queue implemented using the
Vector class


Note that mbox is neither created by Producer
nor by Consumer. It is created by Factory,
which simulates the kernel.


try {


Thread.sleep(1000);


}


catch (InterruptedException ie) {


// do something or do nothing

}

4.
23

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Java Threads
-

Producer
-
Consumer

4.
24

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Threading Issues


Semantics of
fork()

and
exec()

system calls


Thread cancellation
of
target thread


Asynchronous or deferred


Signal
handling


Thread pools


Thread
-
specific data


Scheduler activations

4.
25

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Semantics of fork() and exec()


Does
fork()

duplicate only the calling thread or all threads?


Some UNIX systems have two versions of fork(), one that duplicates all
threads and the other that duplicates only the thread that invoked the
fork() system call.



If exec() is called

immediately after forking, duplicating all threads is
unnecessary
because the program specified in the parameter to exec()
will replace the process



If the separate process does not call exec()

after forking, the separate
process should duplicate all threads

4.
26

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Thread Cancellation


Examples

of terminating a thread before it has finished:



1. multiple threads searching through a database and one returns the
result,
the remaining threads might be cancelled
.



2. multiple threads downloading images of a web page and the user press
the stop button,
all threads loading the page are cancelled
.




Two general approaches:



A thread that is to be cancelled is often referred to as the
target thread




Asynchronous cancellation

terminates the target thread
immediately



Deferred cancellation

allows the
target thread
to
periodically check if it should be cancelled


4.
27

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Thread Cancellation

Deferred cancellation in Java
:
Checking interruption status

Checks its interruption status
, i.e., tests
if
the current
thread has been interrupted.

It is checked periodically because it is inside a while
loop.

returns a reference to the currently
executing thread object

// gets out of the while loop

4.
28

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Thread Cancellation

Deferred cancellation in Java:

Interrupting a thread
:


An instance of an InterruptibleThread can be interrupted
using the following code.

The interruption status of the target thread is set (by the thread
that calls
thrd.interrupt()
).


The interrupt() method only set the interruption status; it is up to
the target thread (
thrd

in this example) to check this status
periodically and determine if it should be canceled.

4.
29

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Signal Handling


Signals

are used in UNIX systems to notify a process that a particular event has
occurred, sometimes called “software interrupt”.



Signals

can be sent by one process to another (or to itself), or by thekernel to a
process.



Signals

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 then handled or ignored



Options in Multithreaded Processes:


Deliver the signal to the thread to which the signal applies


(eg., synchronous signals: ill. mem access, div by 0)


Deliver the signal to every thread in the process


(eg., CTRL <C>)


Deliver the signal to certain threads in the process



(eg., asynchronous signals : external to the running process,


delivered only to those that are not blocking it)


Assign a specific thread to receive all signals for the process


A signal can be delivered via
kill (pid_t pid, int signal)


standard
Unix system call


pthread_kill (pthread_t tid, int signal)


POSIX Pthread

4.
30

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Thread Pools


Create a number of threads in a pool where they await work at
process startup



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

4.
31

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Thread Specific Data (TSD)


Allows each thread to have its own copy of data. Each thread
possesses a private memory block, the TSD area.



For Pthread, this area is indexed by TSD keys. The value
associated with a given TSD key can be different in each thread.
The TSD can be viewed as a two
-
dimensional array of values, with
keys serving as the row index and thread IDs as the column index.
For example,


Threads



T1

T2

T3

T4



K1

6 56 4 1

Keys K2

87 21 0 9


K3

23
12

61
2



K4

11 76 47 88



In Java, thread local variables are implemented by the
ThreadLocal class object.

4.
32

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Scheduler Activations


Both
M:M

and
Two
-
level models
require communication between the
kernel and the thread library for maintaining the appropriate number of
kernel threads allocated to the application


An intermediate data structure, called LWP, is established between the
user and kernel threads.





User



Kernel




Scheduler activations: communication between

the thread library and
the kernel


LWP

LWP

LWP

Threads Library

upcalls

Upcall

handler

4.
33

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Operating System Examples


Linux Thread



Windows XP Threads

4.
34

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Linux Threads


Linux refers to the flow of control within a program as
tasks

rather than
threads



Thread creation
is done through
clone()

system call,
which is passed a set of flags (
see next slide
) that
determine how much sharing is to take place between
the parent and child task.



clone()

allows a child task to share the address space
of the parent task (process), depending on the flags
passed.



Linux provides
fork()
with the traditional functionality of
duplicating a process, as discussed in Chapter 3.

4.
35

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Linux Threads

#include <sched.h>

int clone (int (*fn) (void *), void *child_stack, int flags, void *arg);


clone

creates a new thread that starts with the function pointed to by the
fn

argument (as
opposed to

fork()
which continues with the next command after fork().)


child_stack :
a pointer to a memory space to be used as the stack for the new thread
(which must be
malloc’
ed before that; on most architectures stack grows down, so the
pointer should point at the end of the space),



Flags:

specify what gets inherited from the parent process, and


arg:

is the argument passed to the function. It returns the process ID of the
child_task
or
-
1 on failure.

flags

may also be bitwise
-
or'ed

4.
36

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Windows XP Threads


Implements the
one
-
to
-
one mapping
,
kernel
-
level


Each thread contains


A thread id


Register set


Separate user and kernel stacks


Private data storage area


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), exists
in kernel space


KTHREAD

(kernel thread block), exists
in kernel space


TEB

(thread environment block), exists
in user space


4.
37

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition

Windows XP Threads

Address of the routine in which
the thread starts control

Used when the thread is
running in kernel mode

Used when the thread is
running in user mode

A thread in Windows XP is represented by an ETHREAD block, a data
structure whose members maintain info. About the thread object

Silberschatz, Galvin and Gagne ©2009

Operating System Concepts


8
th

Edition,

End of Chapter 4