98
Thread Programming Chapter #14

Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

  • Upload
    others

  • View
    9

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Thread Programming

Chapter #14

Page 2: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

강의 목차

▶ 스레드 개요▶ POSIX Thread APIs▶ Basic Thread APIs▶ 스레드 프로그램 설계▶ 스레드 동기화▶ Deadlock Problem

Unix System Programming 2Unix System Programming 2

Page 3: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드(Thread) (1)

▶ 스레드(Thread)▶ 하나의 프로그램을 병행 실행하기 위해 나눌 수 있는 작은

크기의 실행단위▶ CPU 스케줄링 객체

▶ 하나의 프로세스는 하나 또는 여러 개의 스레드로 구성된다▶ 프로세스 – 실행중인 프로그램 전체▶ 스레드 – 실행중인 프로그램의 하나의 함수▶ e.g) 프로젝트팀 vs. 프로젝트팀원

▶ 효율적인 병행 실행을 지원하기 위한 구조적 모델을 제공▶ 다중 프로세스(multi-process) 구조는 프로세스 생성 및 프로세

스 스위칭, 프로세스간의 통신 등에 의한 오버헤드가 크다

Unix System Programming 3Unix System Programming 3

Page 4: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드(Thread) (2)

▶ Process vs. Thread

Unix System Programming 4Unix System Programming 4

Process Thread

자원할당 단위 프로그램 실행 단위

프로세스간 상호 독립 스레드간에 프로세스의 자원을공유

IPC를 이용한 통신통신오버헤드가 크다

자원공유를 통한 통신통신 오버헤드가 적다

프로세스 생성 및 문맥교환 오버헤드가 크다

스레드 생성 및 문맥교환 오버헤드가 적다

프로세스 스케줄링 제어가 제약적

스레드 스케줄링 제어가 용이

Page 5: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

5

스레드(Thread) (3)

Unix System Programming

Page 6: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

6

▶ Single Threaded and Multithreaded Process Models

▶ Thread Control Block contains a register image, thread priority and thread state information

스레드(Thread) (4)

Unix System Programming

Page 7: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

7

▶ Thread Control Block(TCB)▶ 스레드 생성 및 제어 정보를 가진 자료구조

▶ e.g) PCB(Process Control Block)

▶ 구성 내용 :▶ Thread ID▶ Register Image▶ Signal Mask▶ Scheduling Priority▶ Thread State

▶ 일부 내용는 스레드가 생성될 때에 프로세스로부터 상속

스레드(Thread) (5)

Unix System Programming

Page 8: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드(Thread) (6)

▶ 스레드 유형▶ 사용자 수준 스레드(ULT: User-Level Thread)▶ 커널 수준 스레드(KLT: Kernel-Level Thread)▶ 경량 프로세스(LWP: Light-Weight Process)

Unix System Programming 8Unix System Programming 8

Page 9: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

▶ 사용자 수준 스레드(ULT)

▶ OS(커널)은 스레드를 지원하지 않음 프로세스가 실행단위

▶ 응용 프로그램이 thread library을 이용하여 쓰레드를생성하여 관리한다

▶ Thread switching은 kernel mode privileges을 요구하지않는다 (no mode switch)

▶ 쓰레드 간의 실행 스케줄링은응용 프로그램에 의해 제어가능

▶ 예: Linux O.S9

스레드(Thread) (7)

Unix System Programming

Page 10: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

▶ 커널 수준 스레드(KLT)

▶ O.S(커널)이 스레드를 생성, 관리한다

▶ 커널은 프로세스와 쓰레드에대한 문맥 정보(context information) 을 유지한다

▶ 커널이 쓰레드 간의 전환을수행한다

▶ 커널이 쓰레드 스케줄링을 수행한다

▶ thread library가 없으며 커널스레드 기능에 대한 API가 지원된다

▶ 예: Windows NT and OS/2

10

스레드(Thread) (8)

Unix System Programming

Page 11: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

▶ 결합형 스레드

▶ 스레드 생성은 응용 프로그램에 의해 수행

▶ 응용 프로그램에 의해 사용자 수준 스레드와 커널 레벨스레드간의 맵핑

▶ 스레드 스케줄링과 동기화가사용자 공간에서 수행

▶ 경량 프로세스(Light-Weight Process)

▶ 사용자 수준 스레드와 커널수준 스레드간의 맵핑 객체

▶ 예: Solaris

11

스레드(Thread) (9)

Unix System Programming

Page 12: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드(Thread) (10)

▶ 경량 프로세스(Light Weight Process)

▶ Process 2 is equivalent to a pure ULT approach▶ Process 4 is equivalent to a pure KLT approach▶ We can specify a different degree of parallelism (process 3 and 5)

1212

Page 13: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Pthread APIs (1)

▶ IEEE POSIX Section 1003.1c▶ IEEE( Institute of Electric and Electronic Engineering )▶ POSIX ( Portable Operating System Interface )▶ Pthread is a standardized model for dividing a program

into subtasks whose execution can be interleaved or run in parallel

▶ Specifics are different for each implementation▶ Mach Threads and NT Threads

▶ Pthread of Linux is kernel level thread ▶ implemented by clone() system call

Unix System Programming 13Unix System Programming 13

Page 14: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Pthread APIs (2)

▶ The subroutines which comprise the PthreadsAPI can be informally grouped into three major classes:

1. Thread management▶ The first class of functions work directly on threads -creating, detaching,

joining, etc. ▶ Includes functions to set/query thread attributes

2. Mutexes▶ The second class of functions deal with synchronization, calleda "mutex",

which is an abbreviation for "mutual exclusion".▶ Mutex functions provide for creating, destroying, locking and unlocking

mutexes. ▶ Mutex attribute functions set or modify attributes associated with mutexes.

3. Condition variables▶ The third class of functions address communications between threads that

share a mutex. ▶ They are based upon programmer specified conditions. And this class

includes functions to create, destroy, wait and signal based upon specified variable values.

▶ Functions to set/query condition variable attributes are also included. 1414

Page 15: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Pthread APIs (3)

▶ The Pthreads API contains over 60 subroutines.▶ focus on a subset of these -specifically, those which are

most likely to be immediately useful to the beginning Pthreads programmer.

▶ The “pthread.h” header file must be included in each source file using the Pthreads library.

▶ The current POSIX standard is defined only for the C language.

Unix System Programming 15Unix System Programming 15

Page 16: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Pthread APIs (4)

▶ Basic Pthreads APIs▶ pthread_create(): thread를 생성▶ pthread_exit(): process를 종료하지 않고, Thread만 종료▶ pthread_join(): thread 수행이 종료되기를 기다림▶ pthread_kill(): thread에게 signal을 보냄▶ pthread_detach(): thread가 종료시에 자원을 해제하도록 설정▶ pthread_equal(): 두 thread ID가 동일한지 검사▶ pthread_self(): 자신의 thread ID를 얻는다▶ pthread_cancel(): 다른 thread의 수행을 취소

Unix System Programming 16Unix System Programming 16

Page 17: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Pthread APIs (5)

▶ Pthreads API program skeleton▶ 다음의 두 개의 헤드파일을 포함

<pthread.h><sched.h>

▶ Compilation Options▶ gcc –D_REENTRANT –lpthread –o x x.c▶ gcc –mt –o x x.c▶ Option “-mt” = “–D_REENTRANT –lpthread”

Unix System Programming 17Unix System Programming 17

Page 18: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Pthread APIs (6)

▶ POSIX 스레드 지원 모드 확인

Unix System Programming 18Unix System Programming 18

// ex14-1.c#include <stdio.h>#include <unistd.h>#include <pthread.h>

int main(void) {

printf(“POSIX version is set to %ld\n”, _POSIX_VERSION);if (_POSIZ_VERSION < 199506L) {

if (_POSIX_X_SOURCE >= 199506L) {printf(“Sorry, your system doesn’t support POSIX.1c threads\n”);

} else {printf(“”Try again with –D_POSIX_C_SOURCE=199506L\n”);

}}else {

printf(“Your system support POSIX.1c thread,\n”);#ifdef _POSIX_THREAD_PRIORITY_SCHEDULING

printf(“including support for thread priority scheduling\n”);#else

printf(“but does not support thread priority scheduling\n”);#endif

}exit(EXIT_SUCCESS);

}

Page 19: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (1)

▶ POSIX 스레드 생성▶ Initially, your main() program comprises a single, default

thread. All other threads must be explicitly created by the programmer

▶ POSIX thread 생성 API

▶ Creates a new thread and makes it executable▶ Once created, threads are peers, and may create other threads

1919

#include <pthread.h>

int pthread_create(pthread_t* tid_p, const pthread_attr_t* attr,void* (*fp)(void*), void *argp)

/* pthread_t* tid_p: 생성된 스레드 ID 반환 변수 *//* const pthread_attr_t* attr: 생성된 스레드에 설정되는 속성값 *//* void* (*fp)(void*): 생성된 스레드가 실행하는 함수 포인터 *//* void *argp: 스레드가 실행하는 함수에 전달되는 매개변수 *//* 정상 종료하면 0를 반환하고, 에러가 발생한 경우에는 -1를 반환한다. 외부변수 errno에 에러를 나타내는 값을 설정한다 */

Unix System Programming

Page 20: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (2)

▶ POSIX 스레드 생성 (계속)

▶ POSIX 스레드 모드▶ 연결된 스레드(joinable thread)

▶ Main 스레드와 연결된 스레드로서 부모와 자식 관계를 가짐▶ Main 스레드는 비분리 스레드가 종료할 때까지 대기하여야 함

▶ 분리된 스레드(detached thread)▶ Main 스레드와의 연결이 끊어진 스레드로서 독립적인 동작 모드

를 가짐▶ Main 스레드는 분리된 스레드에 대해 종료를 대기할 필요가 없다

▶ 분리된 스레드 생성▶ pthread_attr_detachstate()를 이용하여 속성값을 detach mode

로 설정한 후에 스레드를 생성▶ pthread_detach() 호출하여 생성 후에 분리

2020Unix System Programming

Page 21: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (3)

▶ POSIX 스레드 속성 다루기▶ POSIX 스레드 속성 객체 초기화 및 제거

▶ pthread_attr_init() – 파라미터를 통해 전달된 스레드 속성 객체를초기화한다

▶ pthread_attr_destroy() – 초기화된 스레드 속성 객체를 제거한다

2121

#include <pthread.h>

int pthread_attr_init(pthread_attr_t *attr)int pthread_attr_destroy(pthread_attr_t *attr)

Unix System Programming

Page 22: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (4)

▶ POSIX 스레드 속성 다루기 (계속)

▶ POSIX 스레드 속성 검사 및 설정

2222

속성 검사 APIs 설정 APIs

경쟁 영역 pthread_attr_getscope pthread_attr_setscope

스택 크기 pthread_attr_getstacksize pthread_attr_setstacksize

스택 주소 pthread_attr_getstackaddr pthread_attr_setstackaddr

분리 상태 pthread_attr_getdetachstate pthread_attr_setdetachstate

스케줄 정책 pthread_attr_getschedpolicy pthread_attr_setschedpolicy

스케줄 파라미터 pthread_attr_getschedparam pthread_attr_setschedparam

Unix System Programming

Page 23: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (5)

▶ POSIX 스레드 속성 다루기 (계속)

▶ pthread_attr_getxxx(pthread_attr_t *attr, void* attrval_p)▶ 1st parameter – 속성값을 검사할 속성 객체▶ 2nd parameter – 검사한 속성값을 저장한 변수 포인터

– 검사 API에 따라 지정되는 변수 유형이 달라진다

▶ pthread_arrt_setxxx(pthread_attr_t *attr, int attr_type)▶ 1st parameter – 설정할 속성값을 가지고 있는 속성 객체▶ 2nd parameter – 설정할 속성값의 종류를 지정하는 상수▶ 예:

pthread_attr_t *lpattr;…

pthread_attr_setscope(lpattr, PTHREAD_SCOPE_SYSTEM);

2323Unix System Programming

Page 24: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (6)

▶ POSIX 스레드 속성 다루기 (계속)

▶ POSIX 스레드 scope 속성▶ 스레드에 대한 관리 영역 범위를 지정▶ PTHREAD_SCOPE_SYSTEM – 사용자 수준 스레드

▶ 스레드 라이브러리를 통해 관리하며 스케줄링 수행▶ Linux O.S

▶ PTHREAD_SCOPE_PROCESS – 커널 수준 스레드▶ 커널에 의해 관리되며 스케줄링이루어짐▶ Solaris O.S

2424Unix System Programming

Page 25: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (7)

▶ POSIX 스레드 속성 다루기 (계속)

▶ POSIX 스레드 scope 속성 검사 및 설정

2525

#include <pthread.h> #include <stdlib.h> #include <stdio.h>

int main() { pthread_attr_t pattr; int scope;pthread_attr_init(&pattr);pthread_attr_setscope(&pattr, PTHREAD_SCOPE_PROCESS);pthread_attr_getscope(&pattr, &scope); if (scope == PTHREAD_SCOPE_SYSTEM) {

printf("user mode thread\n"); } else if (scope == PTHREAD_SCOPE_PROCESS) {

printf("Kernel mode thread\n"); } return 1;

}

Unix System Programming

Page 26: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (8)

▶ POSIX 스레드 속성 다루기 (계속)

▶ POSIX 스레드 detach 속성 검사 및 설정▶ PTHREAD_CREAT_JOINABLE / PTHREAD_CREAT_DETACHED

2626

#include <pthread.h> #include <stdlib.h> #include <stdio.h>

pthread_attr_t attr; void *test(void *a) {

int policy; printf("Thread Create\n"); pthread_attr_getdetachstate(&attr,

&policy); if (policy ==

PTHREAD_CREATE_JOINABLE) { printf ("Join able\n");

} else if (policy == PTHREAD_CREATE_DETACHED) {

printf ("Detache\n"); }

}

int main() {

int status; pthread_t p_thread;

pthread_attr_init(&attr); // JOINABLE 상태로 변경하고자 할때pthread_attr_setdetachstate(&attr,

PTHREAD_CREATE_JOINABLE);if (pthread_create(&p_thread, NULL,

test, (void *)NULL) < 0) { exit(0);

} pthread_join(p_thread, (void

**)&status);return 0;

}

Unix System Programming

Page 27: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (9)

▶ POSIX 스레드 종료▶ There are several ways in which a pthread may be

terminated: ▶ The thread returns from its starting function ▶ The thread makes a call to the pthread_exit function ▶ The thread is canceled by another thread via the

pthread_cancel function▶ The entire process is terminated due to a call to either the

exec or exit▶ Pthread 스레드 종료 API

▶ Cleanup handler 함수가 등록되어 있으면 이 함수를 호출하여cleanup 작업을 수행한다

2727

#include <pthread.h>

int pthread_exit(void *status)

Unix System Programming

Page 28: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (10)

▶ POSIX 스레드 종료 (계속)

▶ Routines: pthread_exit(void* status)▶ If main() finishes before the threads it has created, and exits

with pthread_exit(), the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes.

▶ status: The programmer may optionally specify a termination status, which is stored as a void pointer for any thread that may join the calling thread.

▶ Cleanup: the pthread_exit() routine does not close files; any files opened inside the thread will remain open after the thread is terminated

▶ Recommendation: Use pthread_exit() to exit from all threads ...especially main().

2828Unix System Programming

Page 29: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (11)

▶ 예제 - POSIX 스레드 생성 및 종료

2929

// ex14-2.c#include <pthread.h> #define NUM_THREADS 5

void *PrintHello(void* threadid) { printf("₩n%d: Hello World!₩n", threadid); pthread_exit(NULL);

}

int main (int argc, char *argv[]) {

pthread_t threads[NUM_THREADS]; int rc, t;

for(t=0; t < NUM_THREADS; t++) { printf("Creating thread %d₩n", t); rc= pthread_create(&threads[t], NULL, PrintHello, (void *)t);if (rc) {

printf("ERROR; return code from pthread_create() is %d₩n", rc);exit(-1);

}} pthread_exit(NULL);

} Unix System Programming

Page 30: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (12)

▶ POSIX 스레드 종료 대기▶ Main 스레드는 연결된 스레드에 대해서는 실행을 종료할 때

까지 대기하여야 한다▶ Process에 대한 fork() & wait()와 유사하게 동작▶ 스레드 종료에 따른 정리 작업을 수행

▶ POSIX 스레드 종료 대기 API

3030

#include <pthread.h>

int pthread_join(pthread_t th, void **thread_return)

/* pthread_t th: 기다릴 (join)할 스레드 식별자 *//* void **thread_return: 스레드의 반환값. thread_return 이 NULL 이아닐경우 해당 포인터로 스레드 반환값을 받아올 수 있다 *//* 일반적으로 자식 스레드를 생성한 스레드에서 자식 스레드가 종료 대기함으로써 자식 스레드의 자원을 회수하도록 한다 */

Unix System Programming

Page 31: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (13)

▶ POSIX 스레드 종료 대기 (계속)

3131

// ex14-3.c#include <pthread.h>#include <stdio.h> #include <unistd.h> #include <stdlib.h>

// 쓰레드 함수// 1초를 기다린후 파라미터^2 을 반환한다. void *t_function(void *data) {

int num = *((int *)data); printf("num %d\n", num); sleep(1); return (void *)(num*num);

// pthread_exit((void *)(num*num)); }

int main() {

pthread_t p_thread; int thr_id; int status; int a = 100;

thr_id = pthread_create(&p_thread, NULL, t_function, (void *)&a);

if (thr_id < 0) { perror("thread create error : "); exit(0);

}

// 스레드 p_thread 가 종료되길 기다렸다가// 종료 반환값을 가져온다. pthread_join(p_thread, (void *)&status);printf("thread join : %d\n", status);

return 0; }

Unix System Programming

Page 32: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (14)

▶ POSIX 스레드 분리▶ POSIX 스레드 분리 API

▶ 분리된 스레드에 대해서는 main 스레드가 종료 대기를 수행할필요가 없다

3232

#include <pthread.h>

int pthread_detach(pthread_t th, void **thread_return)

/* pthread_t th: main 스레드에서 분리할 스레드 식별자 *//* 스레드가 main 스레드로부터 detach 되었을 경우 해당(detach 된) 스레드가 종료하면 pthread_join()을 호출하지 않더라도 즉시 모든 자원이 해제된다*//* pthread_attr_setdetachstate() 호출를 통해 pthread_create 호출시에 스레드가 detach 되도록 할 수도 있다 */

Unix System Programming

Page 33: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (15)

▶ POSIX 스레드 분리 (계속)

3333

// ex14-4.c#include <pthread.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h>

// 쓰레드 함수// 1초를 기다린후 파라미터^2 을 반환한다. void *t_function(void *data) {

char a[100000]; int num = *((int *)data); printf("Thread Start\n"); sleep(5); printf("Thread end\n");

}

int main() {

pthread_t p_thread; int thr_id; int status; int a = 100;

printf(“Before thread…\n”);thr_id = pthread_create(&p_thread, NULL,

t_function, (void *)&a); if (thr_id < 0) {

perror("thread create error : "); exit(0);

}

// 스레드 p_thread를 detach시킨다pthread_detach(p_thread);pause();

return 0; }

Unix System Programming

Page 34: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (16)

▶ POSIX 스레드 cleanup handler 등록 및 제거▶ Cleanup handler

▶ pthread_exit() 호출에 의해 스레드 실행이 종료될 때에 호출▶ 스레드 실행 시에 할당된 자원을 반환하거나 mutex 잠금 등을 해

제하는 등 스레드 정리 작업을 수행

▶ Cleanup handler 등록 및 제거 API

3434

#include <pthread.h>

void pthread_cleanup_push(void (*routine)(void*), void *arg)void pthread_cleanup_pop(int execute)

/* void (*routine)(void*): 등록하고자 하는 cleanup handler *//* void *arg: cleanup handler 파라미터 *//* int execute: 이 값이 ‘0’이면 등록된 cleanup handler를 제거하고, ‘0’이 아닌 값이면 cleanup handler를 실행한 후에 제거한다 */

Unix System Programming

Page 35: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (17)

▶ POSIX 스레드 cleanup handler 등록 및 제거 (계속)

3535

// ex14-3.c#include <pthread.h>#include <stdio.h> #include <unistd.h> #include <stdlib.h>#include <sys/types.h>

// 쓰레드 함수char *mydata;void cleanup(void *); void *t_function(void *data) {

int num = *((int *)data);int i = 0, a = 1;pthread_cleanup_push(cleanup, (void *)

&a);mydata = (char *)malloc(1000);while(1) {

if (i == 3) { pthread_exit(0); return 1;

} printf("loop %d\n", i); i++;sleep(1);

} pthread_cleanup_pop(0);

}

int main() {

pthread_t p_thread; int thr_id; int status; int a = 100;

thr_id = pthread_create(&p_thread, NULL, t_function, (void *)&a);

if (thr_id < 0) { perror("thread create error : ");exit(0);

} pthread_join(p_thread, (void

**)&status);printf("Join finish\n");

}

// cleanup handler void cleanup(void *myarg) {

printf("thread is clean up\n");printf("resource free\n"); free(mydata);

}

Page 36: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (18)

▶ POSIX 스레드 시그널 처리▶ POSIX 스레드는 시그널을 공유한다

▶ 프로세스에 시그널이 전달되면 프로세스가 생성한 모든 스레드에 시그널이 전달된다

▶ POSIX 스레드의 시그널 처리▶ 스레드는 시그널 마스킹을 통해 특정 시그널만 처리 가능▶ 스레드는 다른 스레드에게 시그널 전송이 가능▶ 스레드는 시그널 전달을 동기적으로 대기 가능

▶ 시그널 처리 관련 APIs

3636

#include <pthread.h>#include <signal.h>

int pthread_sigmask(int mode, sigset_t* newmask, sigset_t* oldmask)int pthread_kill(pthread_t thread, int signo)int sigwait(const sigset_t *sigmask, int *sig);

Unix System Programming

Page 37: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (19)

▶ POSIX 스레드 시그널 처리 (계속)

▶ pthread_sigmask()▶ 1st parameter – masking mode

3737

Mode 의 미

SIG_BLOCKnewmask 인자에 포함된 시그널을 스레드의 신호 마스크에 추가

SIG_UNBLOCKnewmask 인자에 포함된 시그널을 스레드의 신호 마스크로부터 제거

SIG_SETMASKnewmask 인자에 포함된 시그널을 스레드의 신호 마스크로 데체

Unix System Programming

Page 38: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Basic Pthread APIs (20)

▶ POSIX 스레드 식별자 검사▶ 스레드 식별자 검사 API

3838

#include <pthread.h>

pthread_t pthread_self(void)

/* 현재 스레드의 식별자를 반환한다 */

Unix System Programming

Page 39: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드 프로그램 설계 (1)

▶ In order for a program to take advantage of pthrea-ds, it must be able to be organized into discrete, in-dependent tasks which can execute concurrently

▶ Splitting▶ CPU-based (e.g., computation)▶ I/O-based (e.g., read data block from a file on disk)

▶ Potential parallelism▶ The property that statements can be executed in any order

without changing the result

Unix System Programming 39Unix System Programming 39

Page 40: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드 프로그램 설계 (2)

▶ Reasons for exploiting potential parallelism▶ Obvious : make a program run faster on a multiprocessor▶ Overlapping I/O

▶ Parallel executing of I/O-bound and CPU-bound jobs▶ e.g.) word processor -> printing & editing

▶ Asynchronous events▶ If one more tasks is subject to the indeterminate occurrence

of events of unknown duration and unknown frequency, it may be more efficient to allow other tasks to proceed while the task subject to asynchronous events is in some unknown state of completion.

▶ e.g.) network-based server

Unix System Programming 40Unix System Programming 40

Page 41: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드 프로그램 설계 (3)

Unix System Programming 41Unix System Programming 41

Page 42: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드 프로그램 설계 (4)

▶ Common models for threaded programs▶ Manager/worker

▶ a single thread, the manager assigns work to other threads, the workers.

▶ Typically, the manager handles all input and parcels out work to the other tasks.

▶ Two forms of the manager/worker model are common: static worker pool and dynamic worker pool.

▶ Pipeline▶ a task is broken into a series of sub operations, each of

which is handled in series, but concurrently, by a different thread.

▶ An automobile assembly line best describes this model. ▶ Peer

▶ similar to the manager/worker model, but after the main thread creates other threads, it participates in the work.

4242Unix System Programming

Page 43: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드 프로그램 설계 (5)

▶ Manager/worker

4343

Manager

Workers

Thread Pool Program

Unix System Programming

Page 44: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드 프로그램 설계 (6)

▶ Manager/worker (계속)

▶ 예제#1 – manager/work model mprogram

4444

main ( void ) /* the manager */{

forever {get a request;switch request

case X : pthread_create( …taskX);case Y : pthread_create( …taskY);

……..}

}

taskX() /* Workers processing requests of type X */{

perform the task, synchronize as needed if accessing shared resources;

done;}

Unix System Programming

Page 45: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드 프로그램 설계 (7)

▶ Manager/worker (계속)

▶ Thread Pool▶ A variant of the Manager/worker model▶ The manager could save some run-time overhead by

creating all worker threads up front

▶ 예제#2 - manager/worker model with a thread pool

4545

main ( void ) /* the manager */{

for the number of workerspthread_create( ….pool_base );forever {

get a request;place request in work queue;signal sleeping threads that work is available;

}}

Unix System Programming

Page 46: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드 프로그램 설계 (8)

▶ Manager/worker (계속)

▶ 예제#2 (계속)

4646

pool_base() /* All workers */{

forever {sleep until awoken by boss;dequeuea work request;switch {

case request X : taskX();case request Y : taskY();….

}}

}

Unix System Programming

Page 47: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드 프로그램 설계 (9)

▶ Pipeline Model

4747Program

Threads

Unix System Programming

Page 48: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드 프로그램 설계 (10)

▶ Pipeline Model - 예제

4848

main (void){

pthread_create( …stage1 );pthread_create( …stage2);

…wait for all pipeline threads to finish;do any clean up;

}

stage1 (){

forever {get next input for the program;do stage1 processing of the input;pass result to next thread in pipeline;

}}

Unix System Programming

Page 49: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드 프로그램 설계 (11)

▶ Pipeline Model – 예제 (계속)

4949

stage2 (){

forever {get input from previous thread in pipeline;do stage2 processing of the input;pass result to next thread in pipeline;

}}…stageN (){

forever {get input from previous thread in pipeline;do stageN processing of the input;pass result to program output;

}}

Unix System Programming

Page 50: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드 프로그램 설계 (12)

▶ Peer Model

5050

Thread Pool Program

Unix System Programming

Page 51: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드 프로그램 설계 (13)

▶ Peer Model - 예제

5151

main (void){

pthread_create( …thread1 …task1 );pthread_create( …thread2 …task2 );

…signal all workers to start;wait for all workers to finish;do any clean up;

}

task1 (){

wait for start;perform task, synchronize as needed if accessing

shared resources;done;

}

Unix System Programming

Page 52: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드 동기화 (1)

▶ Creating thread is the easy part. But, it’s harder to get them to share data properly

▶ 하나의 프로세스 내의 스레드들은 프로세스의 주소공간을 공유한다

▶ Sharing global variables is dangerous two threads may attempt to modify the same variable at the same time

5252Unix System Programming

Page 53: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드 동기화 (2)

▶ Race Conditions▶ 두 개 이상의 스레드가 동시에 동일한 자원을 접근할 수 있다

5353Unix System Programming

Page 54: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드 동기화 (3)

▶ 스레드 동기화 도구(Synchronization Tools)▶ pthread_join function

▶ Allows one thread to suspend execution until another has terminated

▶ Mutex lock functions▶ Mutually exclusive lock▶ Only one thread at a time can hold the lock and access the

data it protects▶ Condition variable functions

▶ An event in which threads have a general interest▶ Pthread library provides ways for threads both to express their

interest in a condition and to signal that an awaited condition has been met

5454Unix System Programming

Page 55: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

스레드 동기화 (4)

▶ 스레드 동기화 도구(Synchronization Tools)▶ Reader/writer exclusion

▶ Allow multiple threads to read data concurrently but any thread writing to the data has exclusive access

▶ Semaphores▶ POSIX real-time extensions(POSIX.1b)

5555Unix System Programming

Page 56: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Mutex Lock (1)

▶ Mutual exclusion (mutex)▶ Exclusive access to data

▶ When one thread has exclusive access to data, other threads can not simultaneously be accessing the same data

▶ Critical section▶ Exclusive access to the code paths or routines that access

data▶ How large does a critical section have to be?

▶ Even a single statement▶ Single statement is no longer atomic at the hardware level

▶ Should always use mutexesto ensure a thread’s shared data operations are atomic with respect to other threads

Unix System Programming 56Unix System Programming 56

Page 57: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Mutex Lock (2)

▶ Using mutex lock in pthread▶ Create and initialize a mutex for each resource you want

to protect, like a record in a database▶ When a thread must access the resource, use

pthread_mutex_lock to lock the resource’s mutex▶ Only one thread at a time can lock the mutex, and others

must wait

▶ When the thread is finished with the resource, unlock the mutex by calling pthread_mutex_unlock

Unix System Programming 57Unix System Programming 57

Page 58: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Mutex Lock (3)

▶ Creating & destroying mutex variables

▶ Mutex variable 은 declare 후, 반드시 초기화되어야 한다▶ Mutex variable 초기화방법

▶ Statically, declare 시:pthread_mutex_t mymutex= THREAD_MUTEX_INITIALIZER;

▶ Thread 실행 중: pthread_mutex_init(mutex, attr) 호출

▶ The mutex is initially unlocked

Unix System Programming 58Unix System Programming 58

#include <pthread.h>

int pthread_mutext_init(pthread_mutex_t *muxp,pthread_mutextattr_t *attrp)

int pthread_mutext_destroy(pthread_mutex_t *muxp)

Page 59: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Mutex Lock (4)

▶ Using mutex lock

▶ pthread_mutex_lock()▶ used by a thread to acquire a lock on the specified mutex var

iable. ▶ If the mutex is already locked by another thread, this call will

block the calling thread until the mutex is unlocked

Unix System Programming 59Unix System Programming 59

#include <pthread.h>

int pthread_mutext_lock(pthread_mutex_t *muxp)int pthread_mutext_trylock(pthread_mutex_t *muxp)int pthread_mutext_unlock(pthread_mutex_t *muxp)

Page 60: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Mutex Lock (5)

▶ Using mutex lock▶ pthread_mutex_unlock()

▶ Unlock a mutex by the owning thread.▶ An error will be returned

▶ If the mutex was already unlocked▶ If the mutex is owned by another thread

▶ pthread_mutex_trylock()▶ Does not suspend its caller if another thread already holds

the mutex, instead, returns immediately▶ Practically, trying and backtracking may cause polling

overhead and starvation▶ Acceptable situation

▶ Real-time programmers to poll for state changes▶ Detecting and avoiding deadlock and priority inversion

Unix System Programming 60Unix System Programming 60

Page 61: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Mutex Lock (6)

▶ 예제 #1 - using mutex lock▶ This example program illustrates the use of mutex variables

in a threads program that performs a dot product.▶ The main data is made available to all threads through a

globally accessible structure. ▶ Each thread works on a different part of the data. ▶ The main thread waits for all the threads to complete their

computations, and then it prints the resulting sum.

Unix System Programming 61Unix System Programming 61

Page 62: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Mutex Lock (7)

▶ 예제 #1 - using mutex lock (계속)

Unix System Programming 62Unix System Programming 62

#include <pthread.h>#include <stdio.h> #include <malloc.h>

typedef struct{double *a; // first vectordouble *b; // second vectordouble sum; // dot product of two vectorsint veclen; // dimension

} DOTDATA;

#define NUMTHRDS 4#define VECLEN 100

DOTDATA dotstr;pthread_t callThd[NUMTHRDS];pthread_mutex_t mutexsum;

Page 63: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Mutex Lock (8)

▶ 예제 #1 - using mutex lock (계속)

Unix System Programming 63Unix System Programming 63

void *dotprod(void *arg) {int i, start, end, offset, len;double mysum, *x, *y;

offset = (int)arg;len= dotstr.veclen;start = offset*len;end = start + len;x = dotstr.a; y = dotstr.b;

/* Perform the dot product */mysum= 0;for (i=start; i < end ; i++) {mysum += (x[i] * y[i]);

}

/* Lock a mutex prior to updating the value in the sharedstructure, and unlock it upon updating. */

pthread_mutex_lock(&mutexsum);dotstr.sum += mysum;pthread_mutex_unlock(&mutexsum);pthread_exit((void*) 0);

}

Page 64: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Mutex Lock (9)

▶ 예제 #1 - using mutex lock (계속)

Unix System Programming 64Unix System Programming 64

int main (intargc, char *argv[]) {int i;double *a, *b;int status;pthread_attr_t attr;

a = (double*) malloc(NUMTHRDS*VECLEN*sizeof(double));b = (double*) malloc(NUMTHRDS*VECLEN*sizeof(double));for (i=0; i < VECLEN*NUMTHRDS; i++) {a[i]=1; b[i]=a[i];

}dotstr.veclen= VECLEN;dotstr.a= a;dotstr.b= b;dotstr.sum=0;

pthread_mutex_init(&mutexsum, NULL);/* Create threads to perform the dot product*/pthread_attr_init(&attr);pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);

Page 65: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Mutex Lock (10)

▶ 예제 #1 - using mutex lock (계속)

Unix System Programming 65Unix System Programming 65

for(i=0;i < NUMTHRDS;i++) {pthread_create( &callThd[i], &attr, dotprod, (void *)i);

}pthread_attr_destroy(&attr);

/* Wait on the other threads */for(i=0;i < NUMTHRDS;i++) {pthread_join( callThd[i], (void **)&status);

}

/* After joining, print out the results and cleanup */printf("Sum = %f ₩n", dotstr.sum);free (a); free (b);pthread_mutex_destroy(&mutexsum);pthread_exit(NULL);

}

Page 66: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Condition Variables (1)

▶ Thread synchronization 도구▶ 특정 조건이 참이 될 때까지 스레드를 블록시키기 위해 사용▶ 항상 mutex lock과 연계하여 사용

▶ 동작 방식:▶ 스레드는 동기화 작업을 위해 우선 mutex lock을 획득하는데, 지정된

조건의 발생을 기다리는 조건 변수가 만족하지 못하면 블록킹된다▶ 스레드가 블록되어 있는 동안 획득했던 mutex lock은 자동으로 해제

된다▶ 다른 스레드가 지정된 조건의 상태를 변경시키면, 조건 변수가 스레

드의 블록 상태를 해제한다▶ 스레드가 블록 상태에서 해제되면 mutext lock을 자동으로 획득하고

다시 조건 검사한다▶ 조건이 거짓이면 스레드는 다시 블록되고, 조건이 참이면 mutext

lock을 해제하고 실행을 계속한다

Unix System Programming 66Unix System Programming 66

Page 67: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Condition Variables (2)

▶ Creating & destroying condition variables▶ Condition variable은 pthread_cond_t type으로선언▶ 사용전에 항상 초기화되어야 한다▶ 초기화 방법

▶ Static한 방법:pthread_cond_t myconvar= PTHREAD_COND_INITIALIZER;

▶ 동적인 방법pthread_cond_init(condition, attr);

Unix System Programming 67Unix System Programming 67

#include <pthread.h>

int pthread_cond_init(pthread_cond_t *condp,pthread_condtattr_t *attrp)

int pthread_cond_destroy(pthread_cond_t *condp)

Page 68: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Condition Variables (3)

▶ Waiting & signaling on condition variables

▶ pthread_cond_wait()▶ specified condition이 signal 될때까지 block되는 함수▶ 반드시 mutex가 locked된 상태에서 호출되어야 하며, 호출되면

자동적으로 mutex를 unlock하고 대기한다.▶ Signal에 의해 깨어날 때에는 mutex는 다시 locked된 상태이다

Unix System Programming 68Unix System Programming 68

#include <pthread.h>

int pthread_cond_wait(pthread_cond_t *condp,pthread_muext_t *muxp)

int pthread_cond_timedwait(pthread_cond_t *condp,pthread_muext_t *muxp, struct timespec *timep)

int pthread_cond_signal(pthread_cond_t *muxp)int pthread_cond_broadcast(pthread_cond_t *muxp)

Page 69: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Condition Variables (4)

▶ Waiting & signaling on condition variables (계속)

▶ pthread_cond_signal()▶ pthread_cond_wait()로 대기하는 thread를 wakeup하는함수이다▶ Mutex가 lock된 상태에서 호출되어야 한다

▶ pthread_cond_broadcast()▶ Condition variable에 대기하는 여러 thread 모두를 깨울 때 사용

된다

▶ pthread_cond_wait()에 의한 대기 thread가 없는 상태에서의pthread_cond_signal() 호출은 no action이다

▶ cond_signal은stack되지않는다

Unix System Programming 69Unix System Programming 69

Page 70: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Condition Variables (5)

▶ 많은 스레드가 대기 상태인 경우▶ If multiple threads are waiting on a condition variable, who

gets awakened first when another thread issues a pthread_cond_signal call?

▶ Scheduling priority▶ First-in first-out order

Unix System Programming 70Unix System Programming 70

Page 71: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Condition Variables (6)

▶ 예제 – using condition variables▶ This simple example program demonstrates the use of

several Pthread condition variable routines.▶ The main routine creates three threads. Two of the threads

perform work and update a "count" variable.▶ The third thread waits until the count variable reaches a

specified value.

Unix System Programming 71Unix System Programming 71

Page 72: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Condition Variables (7)

▶ 예제 – using condition variables (계속)

Unix System Programming 72Unix System Programming 72

#include <pthread.h>#include <stdio.h>

#define NUM_THREADS 3#define TCOUNT 10#define COUNT_LIMIT 12

int count = 0;int thread_ids[3] = {0,1,2};pthread_mutex_t count_mutex;pthread_cond_t count_threshold_cv;

void *inc_count(void *idp) {int i, j;double result=0.0;int *my_id = idp;for (i=0; i < TCOUNT; i++) {pthread_mutex_lock(&count_mutex);count++;

Page 73: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Condition Variables (8)

▶ 예제 – using condition variables (계속)

Unix System Programming 73Unix System Programming 73

/* Check the value of count and signal waiting threadwhen condition is reached. Note that this occurswhile mutex is locked. */

if (count == COUNT_LIMIT) {pthread_cond_signal(&count_threshold_cv);printf("inc_count(): thread %d, count = %dThreshold reached.₩n", *my_id, count);

}printf("inc_count(): thread %d, count = %d, unlockingmutex₩n", *my_id, count);

pthread_mutex_unlock(&count_mutex);

/* Do some work so threads can alternate on mutex lock */for (j=0; j < 1000; j++)result = result + (double)random();

} // for

pthread_exit(NULL);}

Page 74: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Condition Variables (9)

▶ 예제 – using condition variables (계속)

Unix System Programming 74Unix System Programming 74

void *watch_count(void *idp){int *my_id = idp;

printf("Starting watch_count(): thread %d₩n", *my_id);pthread_mutex_lock(&count_mutex);while (count < COUNT_LIMIT) {pthread_cond_wait(&count_threshold_cv, &count_mutex);printf("watch_count(): thread %d Condition signalreceived.₩n", *my_id);

}pthread_mutex_unlock(&count_mutex);pthread_exit(NULL);

}

Page 75: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Condition Variables (10)

▶ 예제 – using condition variables (계속)

7575

int main (intargc, char *argv[]) {int i, rc;pthread_t threads[3];pthread_attr_t attr; // Initialize mutexand condition variable objects

pthread_mutex_init(&count_mutex, NULL);pthread_cond_init(&count_threshold_cv, NULL);/* For portability, explicitly create threads in a joinable state so

that they can be joined later. */pthread_attr_init(&attr);pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);pthread_create(&threads[0], &attr, inc_count, (void *) &thread_ids[0]);pthread_create(&threads[1], &attr, inc_count, (void *) &thread_ids[1]);pthread_create(&threads[2], &attr, watch_count, (void*) &thread_ids[2]);

for (i = 0; i < NUM_THREADS; i++) {pthread_join(threads[i], NULL);

}printf("Main(): Waited on %d threads. Done.₩n",NUM_THREADS);

/* Clean up and exit */pthread_attr_destroy(&attr);pthread_mutex_destroy(&count_mutex);pthread_cond_destroy(&count_threshold_cv);pthread_exit(NULL);

}

Page 76: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Condition Variables (11)

▶ 예제 #2▶ Mutex lock과 조건 변수를 사용하여 다음의 조건을 만족하는 프로

그램을 작성하여라▶ 프로그램 조건:

▶ Reader & writer 스레드를 생성한다▶ Reader 스레드는 사용자로부터 데이터를 읽고 전역 배열 msgbuf를

통해 writer 스레드에 전달한다▶ Writer 스레드는 msgbuf에 있는 데이터를 표준 출력에 출력한다▶ 두 스레드는 사용자로부터 입력이 종료됨을 발견하면 종료한다▶ 두 스레드는 mutex lock과 조건 변수를 통하여 msgbuf 접근을 동기화

한다

7676Unix System Programming

Page 77: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Condition Variables (12)

▶ 예제 #2 (계속)

7777

#include <pthread.h>#include <string.h>#include <stdio.h>#include <signal.h>

#define FINISH() { fprintf(stderr, “%d exits\n”, (int)pthread_self()); \pthread_mutext_unlock(&mutx); pthread_exit(0); return (0); }

pthread_mutext_t mutx;pthread_cond_t condx;int msglen, done;Char msgbuf[256];

void *writer(void *argp){

do {pthread_mutext_lock(&mutx);while (!msglen) {

pthread_cond_wait(&condx, &mutx);if (done) FINISH();

}printf(“*> %s\n”, msgbuf);msglen = 0;pthread_mutex_unlock(&mutx);

} while (1);FINISH();

} Unix System Programming

Page 78: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Condition Variables (13)

▶ 예제 #2 (계속)

7878

void *reader(void *argp){

do {pthread_mutext_lock(&mutx);if (!msglen) {

if (!gets(msgbuf)) break;msglen = strlen(msgbuf) + 1;pthread_cond_signal(&condx);

} else pthread_yeild();pthread_mutex_unlock(&mutx);

} while (1);FINISH();

}

int main(void) {

pthread_t wtid, rtid, tid;

pthread_mutex_init(&mutx, 0);pthread_cond_init(&condx, 0);if (pthread_create(&wtid, NULL, writer, NULL))

perror(“pthread_create”);if (pthread_create(&rtid, NULL, reader, NULL))

perror(“pthread_create”);

Unix System Programming

Page 79: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Condition Variables (14)

▶ 예제 #2 (계속)

7979

if (!pthread_join(rtid, NULL)) {done = 1;pthread_cond_signal(&condx);

}pthread_join(wtid, NULL);

pthread_mutex_destroy(&mutx);pthread_cond_destroy(&condx);pthread_exit(0);

}

Unix System Programming

Page 80: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Reader/Writer Lock (1)

▶ Reasons and rules▶ If a thread tries to get a read lock on a resource, it will

succeed only if no are thread holds a lock on the resource or if all threads that hold a lock are readers

▶ If another thread holds a write lock on the resource, the would-be reader must wait

▶ Conversely, if a thread tries to get a write lock on the resource, it must wait if any other thread holds a read or write lock

8080Unix System Programming

Page 81: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Reader/Writer Lock (2)

▶ Define reader/writer variable of type pthread_rdwr_t

▶ Initialize & destroy reader/write variables▶ pthread_rdwr_init_np: initialize reader/writer lock▶ pthread_rdwr_destroy_np: destroy reader/writer lock

▶ Lock & unlock reader/writer variables▶ pthread_rdwr_rlock_np: obtain read lock▶ pthread_rdwr_wlock_np: obtain write lock▶ pthread_rdwr_runlock_np: release read lock▶ pthread_rdwr_wunlock_np: release write lock

8181Unix System Programming

Page 82: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Reader/Writer Lock (3)

▶ 예제 – Using reader/writer lock

8282

int llist_init(llist_t *llistp){int rtn;llistp->first=NULL;if ((rtn=pthread_rdwr_init_np(&(llistp->rwlock), NULL))!=0) {printf(“pthread_rdwr_init_np error %d”, rtn);exit(1);

}return 0;

}

int llist_insert_data(int index, void* datap, llist_t *llistp){llist_node_t *cur, *prev, *new;int found = FALSE;

pthread_rdwr_wlock_np(&(llistp->rwlock));

Unix System Programming

Page 83: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Reader/Writer Lock (4)

▶ 예제 – Using reader/writer lock (계속)

8383

for(cur=prev=llistp->first;cur!=NULL;prev=cur,cur=cur->nextp) {if (cur->index == index) {free(cur->datap); cur->datap=datap;found=TRUE; break;

} else if(cur->index>index) { break;

}}if (!found) {new = (llist_node_t*)malloc(sizeof(llist_node_t));new->index=index; new->datap=datap; new->nextp=cur;if (cur==llistp->first)llistp->first=new;

elseprev->nextp= new;

}pthread_rdwr_wunlock_np(&(llistp->rwlock));return 0;

}

Unix System Programming

Page 84: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Reader/Writer Lock (5)

▶ 예제 – Using reader/writer lock (계속)

8484

int llist_find_data(int index, void **datapp, llist_t *llistp){llist_node_t *cur, *prev;/* Initialize to “not found”*/*datapp= NULL;pthread_rdwr_rlock_np(&(llistp->rwlock));/* Look through index for our entry */for (cur=prev=llistp->first;cur!=NULL;prev=cur, cur=cur->nestp) {if (cur->index == index) {*datapp=cur->datap; break; }else if (cur->index>index) { break; }

}pthread_rdwr_runlock_np(&(llistp->rwlock));return 0;

}

Unix System Programming

Page 85: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Semaphore (1)

▶ Review of mutex▶ most popular primitives▶ easy to use

▶ easy to understand what it is

▶ prone to errors▶ programmers forget to unlock▶ what if another thread forgets to use lock▶ very difficult to understand programs that contain it

8585Unix System Programming

Page 86: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Semaphore (2)

▶ Why semaphore?▶ Mutex may result in busy-waiting▶ Mutex is only for “mutual exclusion”-no sharing▶ no guarantee of fairness

▶ Semaphore▶ a shared variable with two attributes

▶ integer value: number of threads that can share this semaphore▶ allows n threads to share

▶ thread list: list of threads waiting for this semaphore▶ guarantees FIFO order

▶ Operations▶ cc [ flag ... ] file ... -lposix4 [ library ... ] /* lib for real time extension */▶ #include <semaphore.h>

int sem_init(sem_t *sem, int pshared, unsigned int value );▶ pshared: if non-zero, it is shared between processes

▶ i.e., zero means that it will be used between threads

8686Unix System Programming

Page 87: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Semaphore (3)

▶ Operations▶ int sem_wait(sem_t *sem);▶ int sem_trywait(sem_t *sem);

▶ if the integer value > 0, decrement it and proceedselse block (or fail for trywait)

▶ int sem_post(sem_t *sem);▶ if there is a thread waiting,

wake up a thread according to its schedparam▶ ptread_attr_setschedparm();

else increment the integer value

▶ int sem_destroy(sem_t *sem);▶ other combination:

sem_open(), sem_close()

8787Unix System Programming

Page 88: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Semaphore (4)

▶ Mutex lock vs. Semaphore

8888Unix System Programming

void producer_function(void){while(1){pthread_mutex_lock(&mutex);if ( buffer_has_item == 0 ){buffer = make_new_item();buffer_has_item = 1;

}pthread_mutex_unlock(&mutex);pthread_delay_np(&delay);

}}

void consumer_function(void){while(1){pthread_mutex_lock(&mutex);if ( buffer_has_item == 1){consume_item( buffer );buffer_has_item = 0;

}pthread_mutex_unlock(&mutex);pthread_delay_np(&delay);

}}

Page 89: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Semaphore (5)

▶ Mutex lock vs. Semaphore (계속)

8989Unix System Programming

void producer_function(void){while(1){

semaphore_down(&writers_turn);buffer = make_new_item();semaphore_up(&readers_turn);

}}

void consumer_function(void){while(1){

semaphore_down(&readers_turn);consume_item(buffer);semaphore_up(&writers_turn);

}}

Page 90: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Semaphore (6)

▶ 예제 #3▶ 예제 #2 프로그램을 세마포어를 사용하여 수정하여라

▶ Mutex lock & condition variable a semaphore

9090Unix System Programming

Page 91: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Semaphore (7)

▶ 예제 #3 (계속)

9191Unix System Programming

#include <pthread.h>#include <string.h>#include <stdio.h>#include <semaphore.h>

#define FINISH() { fprintf(stderr, “%d exits\n”, (int)pthread_self()); \pthread_mutext_unlock(&mutx); pthread_exit(0); return (0); }

sem_t semx;int msglen, done = 0;Char msgbuf[256];

void *writer(void *argp){

do {sem_wait(&semx);if (msglen) {

printf(“*> %s\n”, msgbuf);msglen = 0;

}sem_post(&semx);pthread_yeild();

} while (!done);FINISH();

}

Page 92: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Semaphore (8)

▶ 예제 #3 (계속)

9292Unix System Programming

void *reader(void *argp){

do {sem_wait(&semx);if (!msglen) {

if (fgets(msgbuf, 256, stdin))msglen = strlen(msgbuf) + 1;

else done = 1;}sem_post(&semx); pthread_yeild();

} while (!done);FINISH();

}

int main(void) {

pthread_t wtid, rtid, tid;

sem_init(&semx, 0, 0);if (pthread_create(&wtid, NULL, writer, NULL))

perror(“pthread_create”);if (pthread_create(&rtid, NULL, reader, NULL))

perror(“pthread_create”);

Page 93: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Semaphore (9)

▶ 예제 #3 (계속)

9393Unix System Programming

while (!pthread_join(rtid, NULL));pthread_join(wtid, NULL);

sem_destroy(&semx);pthread_exit(0);

}

Page 94: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Deadlock Problem (1)

▶ A set of blocked processes each holding a resource and waiting to acquire a resource held by another process in the set▶ Hold & wait

▶ Circular waiting

▶ Example #1▶ System has 2 tape drives.

▶ P1 and P2 each hold one tape drive and each needs another one.

▶ Example #2▶ semaphores A and B, initialized to 1

P0 P1

wait(A); wait(B);

wait (B); wait(A);

9494Unix System Programming

Page 95: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Deadlock Problem (2)

▶ Bridge Crossing

▶ Traffic only in one direction.▶ Each section of a bridge can be viewed as a resource.▶ If a deadlock occurs, it can be resolved if one car backs up

(preempt resources and rollback).▶ Several cars may have to be backed up if a deadlock occurs.▶ Starvation is possible.

9595Unix System Programming

Page 96: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Deadlock Problem (3)

▶ Traffic Crossing

9696Unix System Programming

Page 97: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Deadlock Problem (4)

▶ Resource Aquisition

9797Unix System Programming

Page 98: Chapter #14mclab.silla.ac.kr/lecture/200801/sp/sp-14.pdf · 2014-05-18 · Pthread APIs (2) The subroutines which comprise the PthreadsAPIcan be informally grouped into three major

Deadlock Problem (5)

▶ Memory Management▶ Space is available for allocation of 200Kbytes, and the

following sequence of events occur

▶ Deadlock occurs if both processes progress to their second request

9898Unix System Programming

P1

…Request 80 Kbytes;

…Request 60 Kbytes;

P2

…Request 70 Kbytes;

…Request 80 Kbytes;