540 likes | 553 Vues
Learn about threads in OS, their benefits over processes, multi-threaded processes, user vs. kernel threads, and examples of thread usage in various OS.
E N D
Chapter 4: Threads • Overview • Multithreading Models • Threading Issues • Pthreads • Windows XP Threads • Linux Threads • Java Threads
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 (orheavyweight) process has a single thread of control
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
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
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 ?
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..
Benefits • Responsiveness • Resource Sharing • Economy • Utilization of MP Architectures Multithread
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
Threads Sharing • Resource sharing.Changes made by one thread to shared system resources will be seen by all other threads. • File open or close at the process level. • Memory Sharing (Same address, same data).Two pointers having the same value, exist in the same virtual memory and point to the same data. • No copy is needed! • Synchronization required.As resources and memory sharing is possible, explicit synchronization is required by the programmer
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
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
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.
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
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
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.
Linux kernel thread API functions usually called from linux/kthread.h • kthread_create(threadfn, data, namefmt, arg...) • kthread_run(threadfn, data, namefmt, ...)
Many-to-One • Many user-level threads mapped to single kernel thread • Examples: • Solaris Green Threads • GNU Portable Threads
One-to-One • Each user-level thread maps to kernel thread • Examples • Windows NT/XP/2000 • Linux • Solaris 9 and later
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
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
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".
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)
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);
#include <stdio.h>#include <stdlib.h>#include <pthread.h> void *print_message_function( void *ptr ); main(){pthread_t thread1, thread2;char *message1 = "Thread 1";char *message2 = "Thread 2";int iret1, iret2;/* Create independent threads each of which will execute function */iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2); /* Wait till threads are complete before main continues. Unless we *//* wait we run the risk of executing an exit which will terminate *//* the process and all threads before the threads have completed. */pthread_join( thread1, NULL);pthread_join( thread2, NULL); printf("Thread 1 returns: %d\n",iret1);printf("Thread 2 returns: %d\n",iret2);exit(0); //main}void *print_message_function( void *ptr ){char *message;message = (char *) ptr;printf("%s \n", message);}
Compile: • C compiler: cc -lpthread pthread1.c or • C++ compiler: g++ -lpthread pthread1.c • Run: ./a.out • Results: Thread 1Thread 2Thread 1 returns: 0Thread 2 returns: 0
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)
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)
#include <malloc.h> #include <sys/types.h> #include <sys/wait.h> #include <signal.h> #include <sched.h> #include <stdio.h> #include <fcntl.h> // 64kB stack #define STACK 1024*64 // The child thread will execute this function int threadFunction( void* argument ) { printf( "child thread entering\n" ); close((int*)argument); printf( "child thread exiting\n" ); return 0; } int main() { void* stack; pid_t pid; int fd; fd = open("/dev/null", O_RDWR); if (fd < 0) { perror("/dev/null"); exit(1); } // Allocate the stack stack = malloc(STACK); 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); if (pid == -1) { perror("clone"); exit(2); } // Wait for the child thread to exit pid = waitpid(pid, 0, 0); if (pid == -1) { perror("waitpid"); exit(3); } // Attempt to write to file should fail, since our thread has closed the file. if (write(fd, "c", 1) < 0) { printf("Parent:\t child closed our file descriptor\n"); } // Free the stack free(stack); return 0; }
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
Java Threads • Java threads are managed by the JVM • Java threads may be created by: • Extending Thread class • Implementing the Runnable interface
Tugas • Buat program sederhana untuk membangkitkan thread dengan perintah hello word • Dengan windows (2 kel) • Degan Linux (2 kel) • Dengan java (2 kel)