chapter 4: threads - iispl() · 2012-09-19 · 4.2 multithread model(cont.) 4.2.2 one-to-one each...

17
Chapter 4: Threads Yoon-Joong Kim Hanbat National University, Computer Engineering Department

Upload: others

Post on 05-Feb-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 4: Threads - IISPL() · 2012-09-19 · 4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread가 blocking system call 해도

Chapter 4: Threads

Yoon-Joong Kim Hanbat National University, Computer Engineering Department

Page 2: Chapter 4: Threads - IISPL() · 2012-09-19 · 4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread가 blocking system call 해도

Chapter 4: Multithreaded Programming

Overview

Multithreading Models

Thread Libraries

Threading Issues

Operating System Examples

Windows XP Threads

Linux Threads

Page 3: Chapter 4: Threads - IISPL() · 2012-09-19 · 4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread가 blocking system call 해도

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 변경 등)

Page 4: Chapter 4: Threads - IISPL() · 2012-09-19 · 4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread가 blocking system call 해도

4.1 Overview(cont.)

Fig. 4.1 Single and Multithreaded Processes

Page 5: Chapter 4: Threads - IISPL() · 2012-09-19 · 4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread가 blocking system call 해도

4.1 Overview(cont.)

Process Address Space ProcessAddress Space with Threads

Address Space of process and thread

Page 6: Chapter 4: Threads - IISPL() · 2012-09-19 · 4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread가 blocking system call 해도

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)

Page 7: Chapter 4: Threads - IISPL() · 2012-09-19 · 4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread가 blocking system call 해도

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 완료까지 다른

모든 스레드들은 대기해야 함

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

Kernel-level threads

커널이 thread생성, 스케줄링, 관리 담당

공평한 스케줄링(fair scheduling)

스위칭 시간이 김(switching is time consuming) : interrupt 처리 때문

blocking I/O system call 수행시 커널이 다른 thread 실행 시킬 수 있음

Examples Windows XP/2000 Solaris Linux Tru64 UNIX Mac OS X

Page 8: Chapter 4: Threads - IISPL() · 2012-09-19 · 4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread가 blocking system call 해도

4.1 Overview(cont.)

User-level Threads vs. Kernel-level Threads

Page 9: Chapter 4: Threads - IISPL() · 2012-09-19 · 4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread가 blocking system call 해도

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

Page 10: Chapter 4: Threads - IISPL() · 2012-09-19 · 4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread가 blocking system call 해도

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 이후 버전

Page 11: Chapter 4: Threads - IISPL() · 2012-09-19 · 4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread가 blocking system call 해도

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

Page 12: Chapter 4: Threads - IISPL() · 2012-09-19 · 4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread가 blocking system call 해도

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

Page 13: Chapter 4: Threads - IISPL() · 2012-09-19 · 4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread가 blocking system call 해도

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); }

pthreads (thrd-posix.c)

Page 14: Chapter 4: Threads - IISPL() · 2012-09-19 · 4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread가 blocking system call 해도

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>

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;

}

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]); 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); } }

Page 15: Chapter 4: Threads - IISPL() · 2012-09-19 · 4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread가 blocking system call 해도

Thread class in C#

Page 16: Chapter 4: Threads - IISPL() · 2012-09-19 · 4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread가 blocking system call 해도

Simple threading scenario ( C# )

Page 17: Chapter 4: Threads - IISPL() · 2012-09-19 · 4.2 Multithread Model(cont.) 4.2.2 One-to-One Each user-level thread maps to kernel thread 한 thread가 blocking system call 해도

Simple threading scenario ( C# )

2nd thread

Write “2nd Th..”

Write “2nd Th..”

Write “2nd Th..”

Write “2nd Th..”

sum=6

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)

3nd thread

Write “3rd Th..” Write “3rd Th..” Write “3rd Th..” Write “3rd Th..” Write “3rd Th..” Write “3rd Th..” Write “3rd Th..”