Download Threads - ukiacrew it

Document related concepts

Linux adoption wikipedia , lookup

Smallfoot wikipedia , lookup

Berkeley Software Distribution wikipedia , lookup

Library (computing) wikipedia , lookup

RSTS/E wikipedia , lookup

Plan 9 from Bell Labs wikipedia , lookup

Burroughs MCP wikipedia , lookup

Mobile operating system wikipedia , lookup

CP/M wikipedia , lookup

Copland (operating system) wikipedia , lookup

Unix security wikipedia , lookup

VS/9 wikipedia , lookup

Spring (operating system) wikipedia , lookup

Distributed operating system wikipedia , lookup

DNIX wikipedia , lookup

Security-focused operating system wikipedia , lookup

Process management (computing) wikipedia , lookup

Thread (computing) wikipedia , lookup

Transcript
Chapter 4: Threads
Chapter 4: Threads
 Overview
 Multithreading Models
 Threading Issues
 Pthreads
 Windows XP Threads
 Linux Threads
 Java Threads
Operating System Concepts
4.2
Silberschatz, Galvin and Gagne ©2005
Process and Thread Reationship
Operating System Concepts
4.3
Silberschatz, Galvin and Gagne ©2005
What is Thread ?
 A basic unit of CPU utilization. It comprises a thread ID, a program
counter, a register set, and a stack.

It is a single sequential flow of control within a program
 It shares with other threads belonging to the same process its code
section, data section, and other OS resources, such as open files
and signals
 A traditional (or heavyweight) process has a single thread of control
Operating System Concepts
4.4
Silberschatz, Galvin and Gagne ©2005
 If a process has multiple threads of control, it can perform more
than one task at a time.
 Threads are a way for a program to split itself into two or more
simultaneously running tasks. That is the real excitement
surrounding threads
Operating System Concepts
4.5
Silberschatz, Galvin and Gagne ©2005
Why Threads?
 A process includes many things: „

An address space (defining all the code and data
pages) „

OS descriptors of resources allocated (e.g., open files) „

Execution state (PC, SP, Execution state (PC, SP, regs,
etc).
 Key idea:

separate the concept of a process (address space, OS
resources, Execution state)

… from that of a minimal “thread of control” (execution
state: stack, stack pointer, program counter, registers) •

Threads are more lightweight, so much faster to create
and switch between than processes
Operating System Concepts
4.6
6
Silberschatz, Galvin and Gagne ©2005
Process vs Thread
 Processes do not share resources very well

Why ?
 Process context switching cost is very high

Why ?
 Communicating between processes is
costly
 Why
Operating System Concepts
?
4.7
Silberschatz, Galvin and Gagne ©2005
Single and Multithreaded Processes
Operating System Concepts
4.8
Silberschatz, Galvin and Gagne ©2005
Thread Examples

A word processor may have a thread for displaying graphics, another
thread for responding to keystrokes from the user, and a third thread for
performing spelling and grammar checking in the background


War game software has soldiers, heroes, farmers, enemy, and kings
Web server can be accessed by more > 1000 users

Open web browser tab

Etc..
Operating System Concepts
4.9
Silberschatz, Galvin and Gagne ©2005
Benefits
 Responsiveness
 Resource Sharing
 Economy
 Utilization of MP Architectures
Multithread
Operating System Concepts
4.10
Silberschatz, Galvin and Gagne ©2005
Per Thread State
 Each Thread has a Thread Control Block (TCB)

Execution State: CPU registers, program counter, pointer
to stack

Scheduling info: State (more later), priority, CPU time

Accounting Info

Various Pointers (for implementing scheduling queues)

Pointer to enclosing process (PCB)

Etc
Operating System Concepts
4.11
Silberschatz, Galvin and Gagne ©2005
Operating System Concepts
4.12
Silberschatz, Galvin and Gagne ©2005
Threads Sharing

Resource sharing.
Changes made by one thread to shared system resources will be seen
by all other threads.
-

Memory Sharing (Same
address, same data).
Two pointers having the same value, exist in the same
virtual memory and point to the same data.
-

File open or close at the process level.
No copy is needed!
Synchronization required.
As resources and memory sharing is possible, explicit synchronization
is required by the programmer
Operating System Concepts
4.13
1
Silberschatz, Galvin and Gagne ©2005
Threads & Process
 Suspending a process involves
suspending all threads of the process
since all threads share the same address
space
 Termination of a process, terminates all
threads within the process
Operating System Concepts
4.14
Silberschatz, Galvin and Gagne ©2005
USER AND KERNEL THREAD
Operating System Concepts
4.15
Silberschatz, Galvin and Gagne ©2005
User Level and Kernel Level Thread
Operating System Concepts
4.16
Silberschatz, Galvin and Gagne ©2005
User Threads
 All thread management is done by the application
 The kernel is not aware of the existence of threads
 Thread switching does not require kernel mode
privileges
 Scheduling is application specific
 Created from three primary thread libraries:

POSIX Pthreads

Win32 threads

Java threads
Operating System Concepts
4.17
Silberschatz, Galvin and Gagne ©2005
 A user-level library multiplex user threads
on top of LWPs and provides facilities for
inter-thread scheduling, context
switching, and synchronization without
involving the kernel.
Operating System Concepts
4.18
Silberschatz, Galvin and Gagne ©2005
Advantages & Disadvantages
 Advantages:

User-level threads does not require modification to operating
systems.

Thread switching does not involve the kernel -- no mode
switching

Scheduling can be application specific -- choose the best
algorithm.

User-level threads can run on any OS -- Only needs a thread
library
 Disadvantages:

Most system calls are blocking and the kernel blocks
processes -- So all threads within the process will be blocked

The kernel can only assign processes to processors -- Two
threads within the same process cannot run simultaneously on
two processors
Operating System Concepts
4.19
Silberschatz, Galvin and Gagne ©2005
Kernel Threads
 Kernel threads may not be as heavy weight as processes,
but they still suffer from performance problems:

All thread management done by Kernel

Any thread operation still requires a system call.

Kernel threads may be overly general


to support needs of different users, languages, etc.
The kernel doesn’t trust the user

there must be lots of checking on kernel calls
 Examples

Windows XP/2000

Solaris

Linux

Tru64 UNIX

Mac OS X
Operating System Concepts
4.20
Silberschatz, Galvin and Gagne ©2005
Advantages & Disadvantages
 Advantages:

Scheduler may need more time for a process having large
number of threads

Kernel-level threads are especially good for applications that
frequently block.
 Disadvantages:

The kernel-level threads are slow and inefficient

Since kernel must manage and schedule threads as well as
processes, there is significant overhead and increased in
kernel complexity.
Operating System Concepts
4.21
Silberschatz, Galvin and Gagne ©2005
Operating System Concepts
4.22
Silberschatz, Galvin and Gagne ©2005
 Linux kernel thread API functions usually
called from linux/kthread.h
 kthread_create(threadfn,
 kthread_run(threadfn,
Operating System Concepts
data, namefmt, arg...)
data, namefmt, ...)
4.23
Silberschatz, Galvin and Gagne ©2005
MULTITHREADING MODELS
Operating System Concepts
4.24
Silberschatz, Galvin and Gagne ©2005
Many-to-One
 Many user-level threads mapped to single kernel thread
 Examples:

Solaris Green Threads

GNU Portable Threads
Operating System Concepts
4.25
Silberschatz, Galvin and Gagne ©2005
Many-to-One Model
Operating System Concepts
4.26
Silberschatz, Galvin and Gagne ©2005
One-to-One
 Each user-level thread maps to kernel thread
 Examples

Windows NT/XP/2000

Linux

Solaris 9 and later
Operating System Concepts
4.27
Silberschatz, Galvin and Gagne ©2005
One-to-one Model
Operating System Concepts
4.28
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
4.29
Silberschatz, Galvin and Gagne ©2005
Many-to-Many Model
Operating System Concepts
4.30
Silberschatz, Galvin and Gagne ©2005
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
Operating System Concepts
4.31
Silberschatz, Galvin and Gagne ©2005
Two-level Model
Operating System Concepts
4.32
Silberschatz, Galvin and Gagne ©2005
Thread libraries
 Thread libraries provide programmers with an API for creating and
managing threads.
 Thread libraries may be implemented either in user space or in kernel
space. The former involves API functions implemented solely within user
space, with no kernel support. The latter involves system calls, and
requires a kernel with thread library support.
 There are three main thread libraries in use today:

POSIX Pthreads

Win32 threads

Java threads .
 The following sections will demonstrate the use of threads in all three
systems for calculating the sum of integers from 0 to N in a separate
thread, and storing the result in a variable "sum".
Operating System Concepts
4.33
Silberschatz, Galvin and Gagne ©2005
Pthreads
 A POSIX standard (IEEE 1003.1c) API for thread creation and synchronization
 API specifies behavior of the thread library, implementation is up to
development of the library
 Common in UNIX operating systems (Solaris, Linux, Mac OS X)
Operating System Concepts
4.34
Silberschatz, Galvin and Gagne ©2005
 Create a thread

pthread_t t;
pthread_create(&t, NULL, func, arg)
 Exit a thread

pthread_exit
 Join two threads

void *ret_val;
pthread_join(t, &ret_val);
Operating System Concepts
4.35
Silberschatz, Galvin and Gagne ©2005
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
/* Wait till threads are complete before main
continues. Unless we */
/* wait we run the risk of executing an exit
which will terminate */
void *print_message_function( void *ptr ); /* the process and all threads before the
threads have completed. */
pthread_join( thread1, NULL);
main()
pthread_join( thread2, NULL);
{
pthread_t thread1, thread2;
printf("Thread 1 returns: %d\n",iret1);
char *message1 = "Thread 1";
printf("Thread 2 returns: %d\n",iret2);
char *message2 = "Thread 2";
exit(0);
int iret1, iret2;
//main
}
/* Create independent threads each of
which will execute function */
void *print_message_function( void *ptr )
iret1 = pthread_create( &thread1, NULL,
{
print_message_function, (void*)
char *message;
message1);
message = (char *) ptr;
iret2 = pthread_create( &thread2, NULL,
printf("%s \n", message);
print_message_function, (void*)
}
message2);
Operating System Concepts
4.36
Silberschatz, Galvin and Gagne ©2005
 Compile:

C compiler: cc -lpthread pthread1.c
or

C++ compiler: g++ -lpthread pthread1.c
 Run: ./a.out
 Results:
Thread 1
Thread 2
Thread 1 returns: 0
Thread 2 returns: 0
Operating System Concepts
4.37
Silberschatz, Galvin and Gagne ©2005
Comparison between Win32 thread and linux pthread
Operating System Concepts
4.38
Silberschatz, Galvin and Gagne ©2005
THREAD BASED ON :
OPERATING SYSTEM
Operating System Concepts
4.39
Silberschatz, Galvin and Gagne ©2005
Windows XP Threads
 Implements the one-to-one mapping
 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)

KTHREAD (kernel thread block)

TEB (thread environment block)
Operating System Concepts
4.40
Silberschatz, Galvin and Gagne ©2005
Operating System Concepts
4.41
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)
Operating System Concepts
4.42
Silberschatz, Galvin and Gagne ©2005
#include <malloc.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <sched.h>
#include <stdio.h>
#include <fcntl.h>
if (stack == 0) {
perror("malloc: could not allocate stack");
exit(1); }
printf("Creating child thread\n");
// Call the clone system call to create the child thread
pid = clone(&threadFunction,
(char*) stack + STACK,
SIGCHLD | CLONE_FS | CLONE_FILES |\
CLONE_SIGHAND | CLONE_VM,
(void*)fd);
// 64kB stack
#define STACK 1024*64
// The child thread will execute this function
int threadFunction( void* argument ) {
printf( "child thread entering\n" );
if (pid == -1) {
close((int*)argument);
perror("clone");
printf( "child thread exiting\n" );
exit(2); }
return 0;
}
// Wait for the child thread to exit
int main()
pid = waitpid(pid, 0, 0);
{
if (pid == -1) { perror("waitpid");
void* stack;
exit(3); }
pid_t pid;
int fd;
// Attempt to write to file should fail, since our thread has closed the fil
fd = open("/dev/null", O_RDWR);
if (write(fd, "c", 1) < 0) {
if (fd < 0) {
printf("Parent:\t child closed our file descriptor\n");
perror("/dev/null");
}
exit(1);
}
// Free the stack
// Allocate the stack
free(stack);
stack = malloc(STACK);
return 0;
}
Operating System Concepts
4.43
Silberschatz, Galvin and Gagne ©2005
 gcc demo.c
 ./a.out
 Result :
Creating child thread
child thread entering
child thread exiting
Parent: child closed our file descriptor
 int clone (int (*fn) (void *), void *child_stack, int flags, void *arg);

int (*fn) (void *), is the thread function to be executed once a
thread starts.

void *child_stack , is a pointer to a stack memory for the child
process.

flags, is the most critical. It allows you to choose the resources
you want to share with the newly created process

void *arg is the argument to the thread function (threadFunction),
and is a file descriprto
Operating System Concepts
4.44
Silberschatz, Galvin and Gagne ©2005
Java Threads
 Java threads are managed by the JVM
 Java threads may be created by:

Extending Thread class

Implementing the Runnable interface
Operating System Concepts
4.45
Silberschatz, Galvin and Gagne ©2005
Java Thread States
Operating System Concepts
4.46
Silberschatz, Galvin and Gagne ©2005
Tugas
1. Buat program sederhana untuk membangkitkan thread dengan
perintah hello word
1.
Dengan windows (2 kel)
2.
Degan Linux (2 kel)
3.
Dengan java (2 kel)
Operating System Concepts
4.47
Silberschatz, Galvin and Gagne ©2005
End of Chapter 4
Operating System Concepts
4.49
Silberschatz, Galvin and Gagne ©2005
Operating System Concepts
4.50
Silberschatz, Galvin and Gagne ©2005
Scheduler Activations
 Both M:M and Two-level models require communication to maintain the
appropriate number of kernel threads allocated to the application
 Scheduler activations, done from Kernel side, will provide upcalls - a
communication mechanism from the kernel to the thread library
 This communication allows an application to maintain the correct number
kernel threads
(a) System call from user thread(1) is blocked by kernel (2)
(b) New kernel thread is created (3). Kernel thread perform upcall to thread library (4).
Thread library creates another user thread to do system call (5)
(c) Sistem call 1 is unblocked (1), preempt the current kernel thread (2), do upcall to thread library
(3) Preempt the new user thread(4) Resume the last blocked user thread.
Operating System Concepts
4.51
Silberschatz, Galvin and Gagne ©2005
#include <linux/module.h>
#include <linux/kernel.h>
static struct task_struct *thread_st; // Function executed by kernel thread
static int thread_fn(void *unused)
{
while (1) {
printk(KERN_INFO "Thread Running\n");
ssleep(5);
}
printk(KERN_INFO "Thread Stopping\n");
do_exit(0);
return 0;
}
Operating System Concepts
4.52
Silberschatz, Galvin and Gagne ©2005
// Module Initialization
static int __init init_thread(void)
{
printk(KERN_INFO "Creating Thread\n");
//Create the kernel thread with name 'mythread'
thread_st = kthread_create(thread_fn, NULL, "mythread");
if (thread_st)
printk("Thread Created successfully\n");
else
printk(KERN_INFO "Thread creation failed\n");
return 0;
}
// Module Exit
static void __exit cleanup_thread(void)
{ printk("Cleaning Up\n"); }
Operating System Concepts
4.53
Silberschatz, Galvin and Gagne ©2005
Lightweight Processes
 LWP is a kernel-supported user thread.
 It belongs to a user process.
 Independently scheduled.
 Share the address space and other
resources of the process.
 LWP should be synchronized on shared
data.
 Blocking an LWP is expensive.
Operating System Concepts
4.54
Silberschatz, Galvin and Gagne ©2005