Threads. Jo, Heeseung

Similar documents
Threads. Jo, Heeseung

POSIX Threads. HUJI Spring 2011

ANSI/IEEE POSIX Standard Thread management

POSIX PTHREADS PROGRAMMING

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Lecture 4. Threads vs. Processes. fork() Threads. Pthreads. Threads in C. Thread Programming January 21, 2005

Threads. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

pthreads CS449 Fall 2017

Pthreads. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Thread and Synchronization

Pthread (9A) Pthread

POSIX threads CS 241. February 17, Copyright University of Illinois CS 241 Staff

THREADS. Jo, Heeseung

The course that gives CMU its Zip! Concurrency I: Threads April 10, 2001

Chapter 4 Threads. Images from Silberschatz 03/12/18. CS460 Pacific University 1

COSC 6374 Parallel Computation. Shared memory programming with POSIX Threads. Edgar Gabriel. Fall References

Posix Threads (Pthreads)

CSE 333 SECTION 9. Threads

Concurrent Programming

Preview. What are Pthreads? The Thread ID. The Thread ID. The thread Creation. The thread Creation 10/25/2017

CSCI4430 Data Communication and Computer Networks. Pthread Programming. ZHANG, Mi Jan. 26, 2017

Threads. studykorner.org

Threads. Threads (continued)

Concurrent Programming

Total Score is updated. The score of PA4 will be changed! Please check it. Will be changed

Computer Systems Laboratory Sungkyunkwan University

LSN 13 Linux Concurrency Mechanisms

Agenda. Process vs Thread. ! POSIX Threads Programming. Picture source:

Synchronization and Semaphores. Copyright : University of Illinois CS 241 Staff 1

Multi-threaded Programming

Introduc)on to pthreads. Shared memory Parallel Programming

pthreads Announcement Reminder: SMP1 due today Reminder: Please keep up with the reading assignments (see class webpage)

Network Programming TDC 561

Introduction to PThreads and Basic Synchronization

Thread. Disclaimer: some slides are adopted from the book authors slides with permission 1

Faculté Polytechnique

Threads. lightweight processes

CSE 333 Section 9 - pthreads

Threads need to synchronize their activities to effectively interact. This includes:

POSIX Threads. Paolo Burgio

EPL372 Lab Exercise 2: Threads and pthreads. Εργαστήριο 2. Πέτρος Παναγή

Parallel Programming with Threads

CS510 Operating System Foundations. Jonathan Walpole

CS-345 Operating Systems. Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization

Introduction to parallel computing

Multithreading Programming II

CS Operating Systems: Threads (SGG 4)

Synchronization and Semaphores. Copyright : University of Illinois CS 241 Staff 1

C Grundlagen - Threads

Lecture 19: Shared Memory & Synchronization

CS 5523 Operating Systems: Thread and Implementation

CS333 Intro to Operating Systems. Jonathan Walpole

HPCSE - I. «Introduction to multithreading» Panos Hadjidoukas

Pthreads: POSIX Threads

Computer Systems Laboratory Sungkyunkwan University

Synchronization Primitives

CSE 306/506 Operating Systems Threads. YoungMin Kwon

real time operating systems course

Operating systems fundamentals - B06

Process Synchronization

CPSC 341 OS & Networks. Threads. Dr. Yingwu Zhu

Concurrent Programming is Hard! Concurrent Programming. Reminder: Iterative Echo Server. The human mind tends to be sequential

Oct 2 and 4, 2006 Lecture 8: Threads, Contd

CS 220: Introduction to Parallel Computing. Condition Variables. Lecture 24

Concurrent Programming

CSci 4061 Introduction to Operating Systems. (Threads-POSIX)

Real Time Operating Systems and Middleware

Concurrent Programming. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

CSC Systems Programming Fall Lecture - XVIII Concurrent Programming. Tevfik Ko!ar. Louisiana State University. November 11 th, 2008

Threads (SGG 4) Outline. Traditional Process: Single Activity. Example: A Text Editor with Multi-Activity. Instructor: Dr.

CS 3305 Intro to Threads. Lecture 6

Unix. Threads & Concurrency. Erick Fredj Computer Science The Jerusalem College of Technology

TCSS 422: OPERATING SYSTEMS

Pthreads (2) Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University Embedded Software Lab.

call connect call read call connect ret connect call fgets Client 2 blocks waiting to complete its connection request until after lunch!

CSCI 4061: Threads in a Nutshell

Interlude: Thread API

Operating System Labs. Yuanbin Wu

Locks and semaphores. Johan Montelius KTH

Concurrent Server Design Multiple- vs. Single-Thread

Concurrency. Johan Montelius KTH

Parallel Computing: Programming Shared Address Space Platforms (Pthread) Jin, Hai

Chapter 4 Concurrent Programming

Approaches to Concurrency

Roadmap. Concurrent Programming. Concurrent Programming. Communication Between Tasks. Motivation. Tevfik Ko!ar

Concurrency and Synchronization. ECE 650 Systems Programming & Engineering Duke University, Spring 2018

What is concurrency? Concurrency. What is parallelism? concurrency vs parallelism. Concurrency: (the illusion of) happening at the same time.

CS345 Opera,ng Systems. Φροντιστήριο Άσκησης 2

Concurrency, Parallel and Distributed

Locks and semaphores. Johan Montelius KTH

CS370 Operating Systems

Threading Language and Support. CS528 Multithreading: Programming with Threads. Programming with Threads

Thread Fundamentals. CSCI 315 Operating Systems Design 1

Warm-up question (CS 261 review) What is the primary difference between processes and threads from a developer s perspective?

Shared Memory Programming Models III

Multithread Programming. Alexandre David

Threads. Today. Next time. Why threads? Thread model & implementation. CPU Scheduling

CS 153 Lab4 and 5. Kishore Kumar Pusukuri. Kishore Kumar Pusukuri CS 153 Lab4 and 5

CSE 421/521 - Operating Systems Fall 2011 Recitations. Recitation - III Networking & Concurrent Programming Prof. Tevfik Kosar. Presented by...

Threads. To do. Why threads? Thread model & implementation. q q q. q Next time: Synchronization

Transcription:

Threads Jo, Heeseung

Multi-threaded program 빠른실행 프로세스를새로생성에드는비용을절약 데이터공유 파일, Heap, Static, Code 의많은부분을공유 CPU 를보다효율적으로활용 코어가여러개일경우코어에 thread 를할당하는방식 2

Multi-threaded program Pros. Cons. 대량의데이터처리에적합 - CPU 자원을효율적으로사용 - 멀티프로세스방식에비해서빠른 thread 생성 데이터교환이쉬움 - IPC 를사용하지않고, 데이터를교환할수있음 기술의성숙 다른기술과융합하기가수월함 프로그래밍난이도상승 - 비직관적 - 문맥의흐름을예상하기어려움 디버깅이어려움 제대로만들기가어려움 - 병렬프로그래밍, 공유자원관리는높은기술숙련도를요구 3

POSIX Thread : pthread POSIX 표준을따르는 pthread Multi thread 프로그래밍을위한 API 를제공 뛰어난호환성 윈도우를제외한모든 Unix 계열운영체제를지원 CPU 각벤더에서도독자적인 thread API 를제공 pthread에비해서뛰어난성능을보여주지만, 이식성과유지 / 보수상의문제로대부분 pthread를이용 4

Posix Threads (pthreads) Interface pthreads: Standard interface for ~60 functions that manipulate threads from C programs Creating and reaping threads - pthread_create() - pthread_join() Determining your thread ID - pthread_self() Terminating threads - pthread_cancel() - pthread_exit() - exit() [terminates all threads], RET [terminates current thread] Synchronizing access to shared variables - pthread_mutex_init - pthread_mutex_[un]lock - pthread_cond_init - pthread_cond_[timed]wait - pthread_cond_signal 5

Thread Create int pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg); thread : pthread_t structure attr : pthread_attr_t start_routine : 스레드함수 arg : 스레드함수로넘길매개변수 6

Thread Create int pthread_join(pthread_t thread, void **value_ptr); thread : pthread_t structure value_ptr : return value pointer 스레드종료후 join 함수를호출해야만자원을회수할수있음 int pthread_detach(pthread_t thread); 해당메인스레드로부터분리함 스레드종료와동시에자원회수 7

The Pthreads "hello, world" Program #include <stdio.h> void *thread(void *vargp); /* thread routine */ void *thread(void *vargp) sleep(1); printf("hello, world!\n"); return NULL; int main() pthread_t tid; # gcc ex.c -lpthread #./a.out main Hello, world! main2 pthread_create(&tid, NULL, thread, NULL); printf("main\n"); pthread_join(tid, NULL); printf("main2\n"); sleep(2); return 0; 8

The Pthreads "hello, world" Program #include <stdio.h> void *thread(void *vargp); /* thread routine */ void *thread(void *vargp) sleep(1); printf("hello, world!\n"); return NULL; int main() pthread_t tid; # gcc ex.c -lpthread #./a.out main main2 Hello, world! pthread_create(&tid, NULL, thread, NULL); printf("main\n"); pthread_detach(tid); printf("main2\n"); sleep(2); return 0; 9

Thread Mutex pthread_mutex_t mutex; int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr); int pthread_mutex_destroy(pthread_mutex_t *mutex); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int pthread_mutex_lock(pthread_mutex_t *mutex); int pthread_mutex_unlock(pthread_mutex_t *mutex); 10

공유 data 를사용하는 threads #include <stdio.h> #include <unistd.h> #include <stdlib.h> #define MAX_THREAD 20 void *t_func(void *data) int *count = (int *)data; int i; pthread_t thread_id = pthread_self(); for (i=0; i<100; i++) *count = *count+1; 11

공유 data 를사용하는 threads int main(int argc, char **argv) pthread_t thread_id[max_thread]; int i = 0; int count = 0; for(i = 0; i < MAX_THREAD; i++) Main Thread : 1957 pthread_create(&thread_id[i], NULL, t_func, (void *)&count); for(i = 0; i < MAX_THREAD; i++) pthread_join(thread_id[i], NULL); # gcc ex.c -lpthread #./a.out Main Thread : 2000 #./a.out printf("main Thread : %d\n", count); return 0; 12

pthread_mutex_lock/unlock #include <stdio.h> #include <unistd.h> #include <stdlib.h> #define MAX_THREAD 20 pthread_mutex_t m_lock; void *t_func(void *data) int *count = (int *)data; int i; pthread_t thread_id = pthread_self(); pthread_mutex_lock(&m_lock); for (i=0; i<100; i++) *count = *count+1; pthread_mutex_unlock(&m_lock); 13

pthread_mutex_lock/unlock int main(int argc, char **argv) pthread_t thread_id[max_thread]; int i = 0; int count = 0; if(pthread_mutex_init(&m_lock, NULL)!= 0) perror("mutex Init failure"); return 1; # gcc ex.c -lpthread #./a.out Main Thread : 2000 for(i = 0; i < MAX_THREAD; i++) pthread_create(&thread_id[i], NULL, t_func, (void *)&count); for(i = 0; i < MAX_THREAD; i++) pthread_join(thread_id[i], NULL); printf("main Thread : %d\n", count); return 0; 14

pthread 동기화 pthread_cond_t cond; int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr); int pthread_cond_destroy(pthread_cond_t *cond); pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex); int pthread_cond_signal(pthread_cond_t *cond); 15

pthread_cond_wait/signal #include <stdio.h> #include <unistd.h> #include <stdlib.h> pthread_mutex_t mut; pthread_cond_t cond; void *f(void *data) printf("before wait\n"); pthread_mutex_lock( &mut ); pthread_cond_wait( &cond, &mut ); printf("after wait\n"); pthread_mutex_unlock( &mut ); return 0; 16

pthread_cond_wait/signal int main(int argc, char *argv[]) int res = 0; res = pthread_mutex_init(&mut, NULL); res = pthread_cond_init(&cond, NULL); pthread_t pt; pthread_create(&pt, NULL, f, NULL); sleep(2); pthread_cond_signal(&cond); # gcc ex.c -lpthread #./a.out before wait after wait pthread_join(pt, NULL); pthread_mutex_destroy(&mut); pthread_cond_destroy(&cond); return 0; 17

pthread_* functions 수많은 pthread 지원을위한함수들이존재 Manual page 참고 man pthreads 18