Chapter 4: Threads Yoon-Joong Kim Hanbat National University, Computer Engineering Department
Chapter 4: Multithreaded Programming Overview Multithreading Models Thread Libraries Threading Issues Operating System Examples Windows XP Threads Linux Threads
4.1 Overview Thread 프로세스에소속된다. 구성요소 : Program counter, register set, stack space 나머지는공유 CPU 스케줄링의기본단위 Dynamic IWP,lightweight process 경량프로세스의문맥교환 ( CPU switching, thread context switch ) : 레지스터세트교환만 ( 예 1) web browser image 와 text 를 display 하는 thread network 에서데이터를가져오는 thread ( 예 2) word processor - graphics 를 display 하는 thread, keystrokes 를읽어오는 thread, spelling 과 grammar 를검사하는 thread Process 다중쓰레드를갖을수있다. code,data section, heap, OS resources ( 쓰레들이공유 ) 와쓰레드들 쓰레드의콘테이너 static A traditional or heavyweight process : a task with one thread 중량프로세스의문맥교환 ( process switching, context switching ) 레지스터세트교환과메모리관련작업도 (virtual memory page table 변경등 )
4.1 Overview(cont.) Fig. 4.1 Single and Multithreaded Processes
4.1 Overview(cont.) Address Space of process and thread Process Address Space ProcessAddress Space with Threads
4.1 Overview(cont.) 제어방식비교 다중스레드제어 (multiple-thread control) : 자신의 PC, stack, 비독립적 (no protection) 다중프로세스제어 (multiple-process control) : 자신의 PC, stack, address space, 독립적 (protection) 스레드의특성 CPU 공유 준비, 수행, 대기상태 자식 thread 생성 block ( 예 ) 생산자소비자문제 2 threads 로구현하면좋음 (better if on 2 processors) ( 예 ) 웹서버구현 Single process architecture : client 의요청을대기해야한다. 대기시간이매우길어짐 Multiple process architecture : client 의요청이있을때새 process 생성, overhead Multithreaded server architecture : client 의요청이있을때새 thread 생성하여서비스한다, 효율적 Thread 의장점 빠른응답 (responsiveness) 자원공유 (resource sharing) 경제성 (economy) 다중처리기구조이용 (utilization of multiprocessor architecture)
4.1 Overview(cont.) User-level Threads vs. Kernel-level Threads User-level threads user level 의 thread library 에서구현 : 라이브러리가 thread 생성, 스케줄링, 관리담당 불공평한스케줄링 (unfair scheduling) 스위칭이빠름 (switching is fast) single thread 인 kernel 에서사용자수준스레드가 blocking I/O system call 을수행핛경우 system call 완료까지다른모든스레드들은대기해야함 Kernel-level threads 커널이 thread 생성, 스케줄링, 관리담당 공평한스케줄링 (fair scheduling) 스위칭시간이김 (switching is time consuming) : interrupt 처리때문 blocking I/O system call 수행시커널이다른 thread 실행시킬수있음 Three primary thread libraries: POSIX pthreads: POSIX (Portable Operating System Interface) standard (IEEE 1003.1c) APIs (Solaris, Linux, Mac OS X) Java Threads Win32 Threads Examples Windows XP/2000 Solaris Linux Tru64 UNIX Mac OS X
4.1 Overview(cont.) User-level Threads vs. Kernel-level Threads
4.2 Multithread Model 4.2.1 Many-to-One Many user-level threads mapped to single kernel thread 한 thread 가 blocking system call 하면전체프로세스 block Examples: 초기의 Solaris Green Threads GNU Portable Threads
4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread 가 blocking system call 해도다른 thread 실행가능 User thread 생성마다 kernel thread 생성해야함 동시성이좋음 (more concurrency): multiprocessors 에서병렬처리 (parallel processing) 가능 Examples Windows 95,98,NT/XP/2000 Linux, Os2 Solaris 9 이후버전
4.2 Multithread Model(cont.) 4.2.3 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 동시성이덜좋음 (less concurrency): 커널은한순간에하나의 kernel thread 만스케줄 특별한경우 : two-level model: 하나의 user-level thread 가하나의 kernel thread 로연결되는경우도지원 : Solaris 8 과이전버전, IRIX, Digital Unix, HP Tru64 UNIX Examples : Solaris 9 이전버전, Windows NT/2000 with the ThreadFiber package
4.2 Multithread Model(cont.) 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
pthreads (thrd-posix.c) 4.3 Thread Libraries #include <pthread.h> #include <stdio.h> int sum; /* this data is shared by the thread(s) */ void *runner(void *param); /* the thread */ main(int argc, char *argv[]) { pthread_t tid; /* the thread identifier */ pthread_attr_t attr; /* set of attributes for the thread */ /* 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); } void *runner(void *param) { int upper = atoi(param); int i; sum = 0; if (upper > 0) { for (i = 1; i <= upper; i++) sum += i; } pthread_exit(0); }
Win 32 API( C ) /** * This program creates a separate thread using the CreateThread() system c * * Figure 4.10 * * @author Gagne, Galvin, Silberschatz * Operating System Concepts - Eighth Edition * Copyright John Wiley & Sons - 2009. */ #include <stdio.h> #include <windows.h> int main(int argc, char *argv[]) { DWORD ThreadId; HANDLE ThreadHandle; int Param; // do some basic error checking if (argc!= 2) { fprintf(stderr,"an integer parameter is required\n"); return -1; } Param = atoi(argv[1]); DWORD Sum; /* data is shared by the thread(s) */ /* the thread runs in this separate function */ DWORD WINAPI Summation(PVOID Param) { DWORD Upper = *(DWORD *)Param; } for (DWORD i = 0; i <= Upper; i++) Sum += i; return 0; } if (Param < 0) { fprintf(stderr, "an integer >= 0 is required \n"); return -1; } // create the thread ThreadHandle = CreateThread(NULL, 0, Summation, &Param, 0, &ThreadId); if (ThreadHandle!= NULL) { WaitForSingleObject(ThreadHandle, INFINITE); CloseHandle(ThreadHandle); printf("sum = %d\n",sum); }
Thread class in C#
Simple threading scenario ( C# )
Simple threading scenario ( C# ) int sum=0; Main thread t2.start() t3.start(8) Do some work Do some work Do some work Do some work t2.join() write(sum) t3.join(8) 2nd thread Write 2 nd Th.. Write 2 nd Th.. Write 2 nd Th.. Write 2 nd Th.. sum=6 3nd thread Write 3rd Th.. Write 3rd Th.. Write 3rd Th.. Write 3rd Th.. Write 3rd Th.. Write 3rd Th.. Write 3rd Th..