1 / 54

Understanding Threads in Operating Systems

Learn about threads in OS, their benefits over processes, multi-threaded processes, user vs. kernel threads, and examples of thread usage in various OS.

wself
Télécharger la présentation

Understanding Threads in Operating Systems

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 4: Threads

  2. Chapter 4: Threads • Overview • Multithreading Models • Threading Issues • Pthreads • Windows XP Threads • Linux Threads • Java Threads

  3. Process and Thread Reationship

  4. 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

  5. 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

  6. 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

  7. 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 ?

  8. Single and Multithreaded Processes

  9. 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..

  10. Benefits • Responsiveness • Resource Sharing • Economy • Utilization of MP Architectures Multithread

  11. 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

  12. 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

  13. 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

  14. USER AND KERNEL THREAD

  15. User Level and Kernel Level Thread

  16. 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

  17. 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.

  18. 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

  19. 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

  20. 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.

  21. Linux kernel thread API functions   usually called from linux/kthread.h • kthread_create(threadfn, data, namefmt, arg...) • kthread_run(threadfn, data, namefmt, ...)

  22. MULTITHREADING MODELS

  23. Many-to-One • Many user-level threads mapped to single kernel thread • Examples: • Solaris Green Threads • GNU Portable Threads

  24. Many-to-One Model

  25. One-to-One • Each user-level thread maps to kernel thread • Examples • Windows NT/XP/2000 • Linux • Solaris 9 and later

  26. One-to-one Model

  27. 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

  28. Many-to-Many Model

  29. 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

  30. Two-level Model

  31. 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".

  32. 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)

  33. 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);

  34. #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);}

  35. 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

  36. Comparison between Win32 thread and linux pthread

  37. THREAD BASED ON : OPERATING SYSTEM

  38. 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)

  39. 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)

  40. #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; }

  41. 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

  42. Java Threads • Java threads are managed by the JVM • Java threads may be created by: • Extending Thread class • Implementing the Runnable interface

  43. Java Thread States

  44. Tugas • Buat program sederhana untuk membangkitkan thread dengan perintah hello word • Dengan windows (2 kel) • Degan Linux (2 kel) • Dengan java (2 kel)

  45. End of Chapter 4

More Related