슬라이드 1

Size: px
Start display at page:

Download "슬라이드 1"

Transcription

1 Thread Programming Chapter #14

2 스레드개요 POSIX Thread APIs Basic Thread APIs 스레드프로그램설계 스레드동기화 Deadlock Problem 강의목차 2

3 스레드 (Thread) 스레드 (Thread) (1) 하나의프로그램을병행실행하기위해나눌수있는작은크기의실행단위 CPU 스케줄링객체 하나의프로세스는하나또는여러개의스레드로구성된다 프로세스 실행중인프로그램전체 스레드 실행중인프로그램의하나의함수 e.g) 프로젝트팀 vs. 프로젝트팀원 효율적인병행실행을지원하기위한구조적모델을제공 다중프로세스 (multi-process) 구조는프로세스생성및프로세스스위칭, 프로세스간의통신등에의한오버헤드가크다 3

4 Process vs. Thread 스레드 (Thread) (2) 자원할당단위 Process 프로세스간상호독립 IPC 를이용한통신 통신오버헤드가크다 프로세스생성및문맥교환오버헤드가크다 프로세스스케줄링제어가제약적 Thread 프로그램실행단위 스레드간에프로세스의자원을공유 자원공유를통한통신 통신오버헤드가적다 스레드생성및문맥교환오버헤드가적다 스레드스케줄링제어가용이 4

5 스레드 (Thread) (3) 5

6 스레드 (Thread) (4) Single Threaded and Multithreaded Process Models Thread Control Block contains a register image, thread priority and thread state information 6

7 스레드 (Thread) (5) Thread Control Block(TCB) 스레드생성및제어정보를가진자료구조 e.g) PCB(Process Control Block) 구성내용 : Thread ID Register Image Signal Mask Scheduling Priority Thread State 일부내용는스레드가생성될때에프로세스로부터상속 7

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

9 스레드 (Thread) (7) 사용자수준스레드 (ULT) OS( 커널 ) 은스레드를지원하지않음 프로세스가실행단위 응용프로그램이 thread library 을이용하여쓰레드를생성하여관리한다 Thread switching 은 kernel mode privileges 을요구하지않는다 (no mode switch) 쓰레드간의실행스케줄링은응용프로그램에의해제어가능 예 : Linux O.S 9

10 스레드 (Thread) (8) 커널수준스레드 (KLT) O.S( 커널 ) 이스레드를생성, 관리한다 커널은프로세스와쓰레드에대한문맥정보 (context information) 을유지한다 커널이쓰레드간의전환을수행한다 커널이쓰레드스케줄링을수행한다 thread library 가없으며커널스레드기능에대한 API 가지원된다 예 : Windows NT and OS/2 10

11 스레드 (Thread) (9) 결합형스레드 스레드생성은응용프로그램에의해수행 응용프로그램에의해사용자수준스레드와커널레벨스레드간의맵핑 스레드스케줄링과동기화가사용자공간에서수행 경량프로세스 (Light-Weight Process) 사용자수준스레드와커널수준스레드간의맵핑객체 예 : Solaris 11

12 스레드 (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) 12

13 Pthread APIs (1) IEEE POSIX Section c 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 13

14 Pthread APIs (2) The subroutines which comprise the PthreadsAPI can be informally grouped into three major classes: 1. Thread management 2. Mutexes The first class of functions work directly on threads -creating, detaching, joining, etc. Includes functions to set/query thread attributes 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. 14

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

16 Basic Pthreads APIs Pthread APIs (4) 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의수행을취소 16

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

18 Pthread APIs (6) POSIX 스레드지원모드확인 // 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 < L) { if (_POSIX_X_SOURCE >= L) { 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); 18

19 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 #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 에에러를나타내는값을설정한다 */ Creates a new thread and makes it executable Once created, threads are peers, and may create other threads 19

20 Basic Pthread APIs (2) POSIX 스레드생성 ( 계속 ) POSIX 스레드모드 연결된스레드 (joinable thread) Main 스레드와연결된스레드로서부모와자식관계를가짐 Main 스레드는비분리스레드가종료할때까지대기하여야함 분리된스레드 (detached thread) Main 스레드와의연결이끊어진스레드로서독립적인동작모드를가짐 Main 스레드는분리된스레드에대해종료를대기할필요가없다 분리된스레드생성 pthread_attr_detachstate() 를이용하여속성값을 detach mode 로설정한후에스레드를생성 pthread_detach() 호출하여생성후에분리 20

21 Basic Pthread APIs (3) POSIX 스레드속성다루기 POSIX 스레드속성객체초기화및제거 #include <pthread.h> int pthread_attr_init(pthread_attr_t *attr) int pthread_attr_destroy(pthread_attr_t *attr) pthread_attr_init() 파라미터를통해전달된스레드속성객체를초기화한다 pthread_attr_destroy() 초기화된스레드속성객체를제거한다 21

22 Basic Pthread APIs (4) POSIX 스레드속성다루기 ( 계속 ) POSIX 스레드속성검사및설정 속성 검사 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 22

23 Basic Pthread APIs (5) POSIX 스레드속성다루기 ( 계속 ) pthread_attr_getxxx(pthread_attr_t *attr, void* attrval_p) 1 st parameter 속성값을검사할속성객체 2nd parameter 검사한속성값을저장한변수포인터 검사 API 에따라지정되는변수유형이달라진다 pthread_arrt_setxxx(pthread_attr_t *attr, int attr_type) 1 st parameter 설정할속성값을가지고있는속성객체 2nd parameter 설정할속성값의종류를지정하는상수 예 : pthread_attr_t *lpattr; pthread_attr_setscope(lpattr, PTHREAD_SCOPE_SYSTEM); 23

24 Basic Pthread APIs (6) POSIX 스레드속성다루기 ( 계속 ) POSIX 스레드 scope 속성 스레드에대한관리영역범위를지정 PTHREAD_SCOPE_SYSTEM 사용자수준스레드 스레드라이브러리를통해관리하며스케줄링수행 Linux O.S PTHREAD_SCOPE_PROCESS 커널수준스레드 커널에의해관리되며스케줄링이루어짐 Solaris O.S 24

25 Basic Pthread APIs (7) POSIX 스레드속성다루기 ( 계속 ) POSIX 스레드 scope 속성검사및설정 #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; 25

26 Basic Pthread APIs (8) POSIX 스레드속성다루기 ( 계속 ) POSIX 스레드 detach 속성검사및설정 PTHREAD_CREAT_JOINABLE / PTHREAD_CREAT_DETACHED #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; 26

27 POSIX 스레드종료 Basic Pthread APIs (9) 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 #include <pthread.h> int pthread_exit(void *status) Cleanup handler 함수가등록되어있으면이함수를호출하여 cleanup 작업을수행한다 27

28 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(). 28

29 Basic Pthread APIs (11) 예제 - POSIX 스레드생성및종료 // 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); 29

30 Basic Pthread APIs (12) POSIX 스레드종료대기 Main 스레드는연결된스레드에대해서는실행을종료할때까지대기하여야한다 Process에대한 fork() & wait() 와유사하게동작 스레드종료에따른정리작업을수행 POSIX 스레드종료대기 API #include <pthread.h> int pthread_join(pthread_t th, void **thread_return) /* pthread_t th: 기다릴 (join) 할스레드식별자 */ /* void **thread_return: 스레드의반환값. thread_return 이 NULL 이아닐경우해당포인터로스레드반환값을받아올수있다 */ /* 일반적으로자식스레드를생성한스레드에서자식스레드가종료대기함으로써자식스레드의자원을회수하도록한다 */ 30

31 Basic Pthread APIs (13) POSIX 스레드종료대기 ( 계속 ) // 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; 31

32 Basic Pthread APIs (14) POSIX 스레드분리 POSIX 스레드분리 API #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 되도록할수도있다 */ 분리된스레드에대해서는 main 스레드가종료대기를수행할필요가없다 32

33 Basic Pthread APIs (15) POSIX 스레드분리 ( 계속 ) // 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; 33

34 Basic Pthread APIs (16) POSIX 스레드 cleanup handler 등록및제거 Cleanup handler pthread_exit() 호출에의해스레드실행이종료될때에호출 스레드실행시에할당된자원을반환하거나 mutex 잠금등을해제하는등스레드정리작업을수행 Cleanup handler 등록및제거 API #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 를실행한후에제거한다 */ 34

35 Basic Pthread APIs (17) POSIX 스레드 cleanup handler 등록및제거 ( 계속 ) // 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); 35

36 Basic Pthread APIs (18) POSIX 스레드시그널처리 POSIX 스레드는시그널을공유한다 프로세스에시그널이전달되면프로세스가생성한모든스레드에시그널이전달된다 POSIX 스레드의시그널처리 스레드는시그널마스킹을통해특정시그널만처리가능 스레드는다른스레드에게시그널전송이가능 스레드는시그널전달을동기적으로대기가능 시그널처리관련 APIs #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); 36

37 Basic Pthread APIs (19) POSIX 스레드시그널처리 ( 계속 ) pthread_sigmask() 1 st parameter masking mode Mode SIG_BLOCK SIG_UNBLOCK SIG_SETMASK 의미 newmask 인자에포함된시그널을스레드의신호마스크에추가 newmask 인자에포함된시그널을스레드의신호마스크로부터제거 newmask 인자에포함된시그널을스레드의신호마스크로데체 37

38 Basic Pthread APIs (20) POSIX 스레드식별자검사 스레드식별자검사 API #include <pthread.h> pthread_t pthread_self(void) /* 현재스레드의식별자를반환한다 */ 38

39 스레드프로그램설계 (1) In order for a program to take advantage of pthreads, it must be able to be organized into discrete, independent 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 39

40 스레드프로그램설계 (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 40

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

42 스레드프로그램설계 (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. 42

43 스레드프로그램설계 (5) Manager/worker Manage r Workers Thread Pool Program 43

44 스레드프로그램설계 (6) Manager/worker ( 계속 ) 예제 #1 manager/work model mprogram 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; 44

45 스레드프로그램설계 (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 main ( void ) /* the manager */ { for the number of workers pthread_create(.pool_base ); forever { get a request; place request in work queue; signal sleeping threads that work is available; 45

46 스레드프로그램설계 (8) Manager/worker ( 계속 ) 예제 #2 ( 계속 ) pool_base() /* All workers */ { forever { sleep until awoken by boss; dequeuea work request; switch { case request X : taskx(); case request Y : tasky();. 46

47 스레드프로그램설계 (9) Pipeline Model Threads Program 47

48 스레드프로그램설계 (10) Pipeline Model - 예제 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; 48

49 스레드프로그램설계 (11) Pipeline Model 예제 ( 계속 ) 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; 49

50 Peer Model 스레드프로그램설계 (12) Thread Pool Program 50

51 스레드프로그램설계 (13) Peer Model - 예제 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; 51

52 스레드동기화 (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 52

53 Race Conditions 스레드동기화 (2) 두개이상의스레드가동시에동일한자원을접근할수있다 53

54 스레드동기화 (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 54

55 스레드동기화 (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) 55

56 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 56

57 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 57

58 Mutex Lock (3) Creating & destroying mutex variables #include <pthread.h> int pthread_mutext_init(pthread_mutex_t *muxp, pthread_mutextattr_t *attrp) int pthread_mutext_destroy(pthread_mutex_t *muxp) 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 58

59 Using mutex lock Mutex Lock (4) #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) 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 59

60 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 60

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

62 Mutex Lock (7) 예제 #1 - using mutex lock ( 계속 ) #include <pthread.h> #include <stdio.h> #include <malloc.h> typedef struct{ double *a; // first vector double *b; // second vector double sum; // dot product of two vectors int veclen; // dimension DOTDATA; #define NUMTHRDS 4 #define VECLEN 100 DOTDATA dotstr; pthread_t callthd[numthrds]; pthread_mutex_t mutexsum; 62

63 Mutex Lock (8) 예제 #1 - using mutex lock ( 계속 ) 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 shared structure, and unlock it upon updating. */ pthread_mutex_lock(&mutexsum); dotstr.sum += mysum; pthread_mutex_unlock(&mutexsum); pthread_exit((void*) 0); 63

64 Mutex Lock (9) 예제 #1 - using mutex lock ( 계속 ) 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); 64

65 Mutex Lock (10) 예제 #1 - using mutex lock ( 계속 ) 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); 65

66 Condition Variables (1) Thread synchronization 도구 특정조건이참이될때까지스레드를블록시키기위해사용 항상 mutex lock 과연계하여사용 동작방식 : 스레드는동기화작업을위해우선 mutex lock을획득하는데, 지정된조건의발생을기다리는조건변수가만족하지못하면블록킹된다 스레드가블록되어있는동안획득했던 mutex lock은자동으로해제된다 다른스레드가지정된조건의상태를변경시키면, 조건변수가스레드의블록상태를해제한다 스레드가블록상태에서해제되면 mutext lock을자동으로획득하고다시조건검사한다 조건이거짓이면스레드는다시블록되고, 조건이참이면 mutext lock을해제하고실행을계속한다 66

67 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); #include <pthread.h> int pthread_cond_init(pthread_cond_t *condp, pthread_condtattr_t *attrp) int pthread_cond_destroy(pthread_cond_t *condp) 67

68 Condition Variables (3) Waiting & signaling on condition variables #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) pthread_cond_wait() specified condition 이 signal 될때까지 block 되는함수 반드시 mutex가 locked된상태에서호출되어야하며, 호출되면자동적으로 mutex를 unlock하고대기한다. Signal에의해깨어날때에는 mutex는다시 locked된상태이다 68

69 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되지않는다 69

70 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 70

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

72 Condition Variables (7) 예제 using condition variables ( 계속 ) #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++; 72

73 Condition Variables (8) 예제 using condition variables ( 계속 ) /* Check the value of count and signal waiting thread when condition is reached. Note that this occurs while mutex is locked. */ if (count == COUNT_LIMIT) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %d, count = %d Threshold reached. n", *my_id, count); printf("inc_count(): thread %d, count = %d, unlocking mutex 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); 73

74 Condition Variables (9) 예제 using condition variables ( 계속 ) 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 signal received. n", *my_id); pthread_mutex_unlock(&count_mutex); pthread_exit(null); 74

75 Condition Variables (10) 예제 using condition variables ( 계속 ) 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); 75

76 Condition Variables (11) 예제 #2 Mutex lock과조건변수를사용하여다음의조건을만족하는프로그램을작성하여라 프로그램조건 : Reader & writer 스레드를생성한다 Reader 스레드는사용자로부터데이터를읽고전역배열 msgbuf를통해 writer 스레드에전달한다 Writer 스레드는 msgbuf에있는데이터를표준출력에출력한다 두스레드는사용자로부터입력이종료됨을발견하면종료한다 두스레드는 mutex lock과조건변수를통하여 msgbuf 접근을동기화한다 76

77 예제 #2 ( 계속 ) Condition Variables (12) #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(); 77

78 예제 #2 ( 계속 ) Condition Variables (13) 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 ); 78

79 예제 #2 ( 계속 ) Condition Variables (14) 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); 79

80 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 80

81 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 81

82 Reader/Writer Lock (3) 예제 Using reader/writer lock 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)); 82

83 Reader/Writer Lock (4) 예제 Using reader/writer lock ( 계속 ) 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; else prev->nextp= new; pthread_rdwr_wunlock_np(&(llistp->rwlock)); return 0; 83

84 Reader/Writer Lock (5) 예제 Using reader/writer lock ( 계속 ) 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; 84

85 Review of mutex Semaphore (1) 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 85

86 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 86

87 Operations Semaphore (3) int sem_wait(sem_t *sem); int sem_trywait(sem_t *sem); if the integer value > 0, decrement it and proceeds else 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() 87

88 Semaphore (4) Mutex lock vs. Semaphore 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); 88

89 Semaphore (5) Mutex lock vs. Semaphore ( 계속 ) 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); 89

90 Semaphore (6) 예제 #3 예제 #2 프로그램을세마포어를사용하여수정하여라 Mutex lock & condition variable a semaphore 90

91 Semaphore (7) 예제 #3 ( 계속 ) #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(); 91

92 Semaphore (8) 예제 #3 ( 계속 ) 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 ); 92

93 Semaphore (9) 예제 #3 ( 계속 ) while (!pthread_join(rtid, NULL)); pthread_join(wtid, NULL); sem_destroy(&semx); pthread_exit(0); 93

94 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 wait(a); wait (B); P1 wait(b); wait(a); 94

95 Bridge Crossing Deadlock Problem (2) 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. 95

96 Traffic Crossing Deadlock Problem (3) 96

97 Deadlock Problem (4) Resource Aquisition 97

98 Deadlock Problem (5) Memory Management Space is available for allocation of 200Kbytes, and the following sequence of events occur P1 Request 80 Kbytes; Request 60 Kbytes; P2 Request 70 Kbytes; Request 80 Kbytes; Deadlock occurs if both processes progress to their second request 98

Microsoft PowerPoint - 11_Thread

Microsoft PowerPoint - 11_Thread Linux 쓰레드 - 기본 - Pthread - 생성과소멸 - 동기화 - 공유변수 - 상호배제 기본? 경량프로세스 (lightweight process: LWP) 일반프로세스는생성시자신만의메모리영역을할당받는다 PCB, code, static, heap, stack 등 : PCB 와스택만별도로할당받고나머지는부모프로세스와공유 생성과전환 (context switch)

More information

10주차.key

10주차.key 10, Process synchronization (concurrently) ( ) => critical section ( ) / =>, A, B / Race condition int counter; Process A { counter++; } Process B { counter ;.. } counter++ register1 = counter register1

More information

6주차.key

6주차.key 6, Process concept A program in execution Program code PCB (process control block) Program counter, registers, etc. Stack Heap Data section => global variable Process in memory Process state New Running

More information

Figure 5.01

Figure 5.01 Chapter 4: Threads Yoon-Joong Kim Hanbat National University, Computer Engineering Department Chapter 4: Multithreaded Programming Overview Multithreading Models Thread Libraries Threading Issues Operating

More information

강의10

강의10 Computer Programming gdb and awk 12 th Lecture 김현철컴퓨터공학부서울대학교 순서 C Compiler and Linker 보충 Static vs Shared Libraries ( 계속 ) gdb awk Q&A Shared vs Static Libraries ( 계속 ) Advantage of Using Libraries Reduced

More information

Microsoft PowerPoint - o6.pptx

Microsoft PowerPoint - o6.pptx Dining-Philosophers Problem 세마포사용 Semaphore chopstick[5] = {1,1,1,1,1} ; // initially all values are 1 Philosopher i while (true) { P(chopStick[i]); // get left chopstick P(chopStick[(i+1) % 5]); // get

More information

Microsoft PowerPoint - o6.pptx

Microsoft PowerPoint - o6.pptx Dining-Philosophers Problem 세마포사용 6.8 모니터 (Monitors) Semaphore chopstick[5] = {1,1,1,1,1 ; // initially all values are 1 Philosopher i while (true) { P(chopStick[i]); // get left chopstick P(chopStick[(i+1)

More information

untitled

untitled Embedded System Lab. II Embedded System Lab. II 2 RTOS Hard Real-Time vs Soft Real-Time RTOS Real-Time, Real-Time RTOS General purpose system OS H/W RTOS H/W task Hard Real-Time Real-Time System, Hard

More information

슬라이드 1

슬라이드 1 / 유닉스시스템개요 / 파일 / 프로세스 01 File Descriptor file file descriptor file type unix 에서의파일은단지바이트들의나열임 operating system 은파일에어떤포맷도부과하지않음 파일의내용은바이트단위로주소를줄수있음 file descriptor 는 0 이나양수임 file 은 open 이나 creat 로 file

More information

Chap04(Signals and Sessions).PDF

Chap04(Signals and Sessions).PDF Signals and Session Management 2002 2 Hyun-Ju Park (Signal)? Introduction (1) mechanism events : asynchronous events - interrupt signal from users : synchronous events - exceptions (accessing an illegal

More information

Abstract View of System Components

Abstract View of System Components 운영체제실습 - Synchronization - Real-Time Computing and Communications Lab. Hanyang University jtlim@rtcc.hanyang.ac.kr dhchoi@rtcc.hanyang.ac.kr beespjh@gmail.com Introduction 조교소개 이름 : 임정택 Tel : 010-4780

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 Network Programming Jo, Heeseung Network 실습 네트워크프로그래밍 멀리떨어져있는호스트들이서로데이터를주고받을수있도록프로그램을구현하는것 파일과는달리데이터를주고받을대상이멀리떨어져있기때문에소프트웨어차원에서호스트들간에연결을해주는장치가필요 이러한기능을해주는장치로소켓이라는인터페이스를많이사용 소켓프로그래밍이란용어와네트워크프로그래밍이랑용어가같은의미로사용

More information

untitled

untitled Step Motor Device Driver Embedded System Lab. II Step Motor Step Motor Step Motor source Embedded System Lab. II 2 open loop, : : Pulse, 1 Pulse,, -, 1 +5%, step Step Motor (2),, Embedded System Lab. II

More information

K&R2 Reference Manual 번역본

K&R2 Reference Manual 번역본 typewriter structunion struct union if-else if if else if if else if if if if else else ; auto register static extern typedef void char short int long float double signed unsigned const volatile { } struct

More information

11¹Ú´ö±Ô

11¹Ú´ö±Ô A Review on Promotion of Storytelling Local Cultures - 265 - 2-266 - 3-267 - 4-268 - 5-269 - 6 7-270 - 7-271 - 8-272 - 9-273 - 10-274 - 11-275 - 12-276 - 13-277 - 14-278 - 15-279 - 16 7-280 - 17-281 -

More information

Chap06(Interprocess Communication).PDF

Chap06(Interprocess Communication).PDF Interprocess Communication 2002 2 Hyun-Ju Park Introduction (interprocess communication; IPC) IPC data transfer sharing data event notification resource sharing process control Interprocess Communication

More information

02 C h a p t e r Java

02 C h a p t e r Java 02 C h a p t e r Java Bioinformatics in J a va,, 2 1,,,, C++, Python, (Java),,, (http://wwwbiojavaorg),, 13, 3D GUI,,, (Java programming language) (Sun Microsystems) 1995 1990 (green project) TV 22 CHAPTER

More information

Microsoft PowerPoint - ch03ysk2012.ppt [호환 모드]

Microsoft PowerPoint - ch03ysk2012.ppt [호환 모드] 전자회로 Ch3 iode Models and Circuits 김영석 충북대학교전자정보대학 2012.3.1 Email: kimys@cbu.ac.kr k Ch3-1 Ch3 iode Models and Circuits 3.1 Ideal iode 3.2 PN Junction as a iode 3.4 Large Signal and Small-Signal Operation

More information

CD-RW_Advanced.PDF

CD-RW_Advanced.PDF HP CD-Writer Program User Guide - - Ver. 2.0 HP CD-RW Adaptec Easy CD Creator Copier, Direct CD. HP CD-RW,. Easy CD Creator 3.5C, Direct CD 3.0., HP. HP CD-RW TEAM ( 02-3270-0803 ) < > 1. CD...3 CD...5

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 Reasons for Poor Performance Programs 60% Design 20% System 2.5% Database 17.5% Source: ORACLE Performance Tuning 1 SMS TOOL DBA Monitoring TOOL Administration TOOL Performance Insight Backup SQL TUNING

More information

13주-14주proc.PDF

13주-14주proc.PDF 12 : Pro*C/C++ 1 2 Embeded SQL 3 PRO *C 31 C/C++ PRO *C NOT! NOT AND && AND OR OR EQUAL == = SQL,,, Embeded SQL SQL 32 Pro*C C SQL Pro*C C, C Pro*C, C C 321, C char : char[n] : n int, short, long : float

More information

Microsoft PowerPoint APUE(Intro).ppt

Microsoft PowerPoint APUE(Intro).ppt 컴퓨터특강 () [Ch. 1 & Ch. 2] 2006 년봄학기 문양세강원대학교컴퓨터과학과 APUE 강의목적 UNIX 시스템프로그래밍 file, process, signal, network programming UNIX 시스템의체계적이해 시스템프로그래밍능력향상 Page 2 1 APUE 강의동기 UNIX 는인기있는운영체제 서버시스템 ( 웹서버, 데이터베이스서버

More information

Page 2 of 5 아니다 means to not be, and is therefore the opposite of 이다. While English simply turns words like to be or to exist negative by adding not,

Page 2 of 5 아니다 means to not be, and is therefore the opposite of 이다. While English simply turns words like to be or to exist negative by adding not, Page 1 of 5 Learn Korean Ep. 4: To be and To exist Of course to be and to exist are different verbs, but they re often confused by beginning students when learning Korean. In English we sometimes use the

More information

1장. 유닉스 시스템 프로그래밍 개요

1장.  유닉스 시스템 프로그래밍 개요 Unix 프로그래밍및실습 7 장. 시그널 - 과제보충 응용과제 1 부모프로세스는반복해서메뉴를출력하고사용자로부터주문을받아자식프로세스에게주문내용을알린다. (SIGUSR1) ( 일단주문을받으면음식이완료되기전까지 SIGUSR1 을제외한다른시그널은모두무시 ) timer 자식프로세스는주문을받으면조리를시작한다. ( 일단조리를시작하면음식이완성되기전까지 SIGALARM 을제외한다른시그널은모두무시

More information

(Asynchronous Mode) ( 1, 5~8, 1~2) & (Parity) 1 ; * S erial Port (BIOS INT 14H) - 1 -

(Asynchronous Mode) ( 1, 5~8, 1~2) & (Parity) 1 ; * S erial Port (BIOS INT 14H) - 1 - (Asynchronous Mode) - - - ( 1, 5~8, 1~2) & (Parity) 1 ; * S erial Port (BIOS INT 14H) - 1 - UART (Univ ers al As y nchronous Receiver / T rans mitter) 8250A 8250A { COM1(3F8H). - Line Control Register

More information

chap7.key

chap7.key 1 7 C 2 7.1 C (System Calls) Unix UNIX man Section 2 C. C (Library Functions) C 1975 Dennis Ritchie ANSI C Standard Library 3 (system call). 4 C?... 5 C (text file), C. (binary file). 6 C 1. : fopen( )

More information

Something that can be seen, touched or otherwise sensed

Something that can be seen, touched or otherwise sensed Something that can be seen, touched or otherwise sensed Things about an object Weight Height Material Things an object does Pen writes Book stores words Water have Fresh water Rivers Oceans have

More information

Microsoft PowerPoint - o4.pptx

Microsoft PowerPoint - o4.pptx 목표 쓰레드 (thread) 개념소개 Thread API Multithreaded 프로그래밍관련이슈 4 장. 쓰레드 2 4.1 개요 쓰레드 쓰레드 (Thread ) CPU 이용의기본실행단위 단일쓰레드 (Single threaded) Processes 전통적인프로세스 한개의실행단위로구성 다중쓰레드 (Multithreaded) Process 여러개의실행쓰레드를갖는프로세스

More information

The Pocket Guide to TCP/IP Sockets: C Version

The Pocket Guide to  TCP/IP Sockets: C Version 중급소켓프로그래밍 (3) 네트워크프로그래밍 6 장 1 목차 제 6장중급소켓프로그래밍 6.1 소켓옵션 6.2 시그널 6.3 넌블로킹입 / 출력 6.4 멀티태스킹 6.5 멀티플렉싱 6.6 다수의수싞자처리 2 멀티태스킹 멀티태스킹이란? 사젂적의미 한사람의사용자가한대의컴퓨터로 2 가지이상의작업을동시에처리하거나, 2 가지이상의프로그램들을동시에실행시키는것 소켓에서의멀티태스킹

More information

- 2 -

- 2 - - 1 - - 2 - - 3 - - 4 - - 5 - - 6 - - 7 - - 8 - - 9 - - 10 - - 11 - - 12 - - 13 - - 14 - - 15 - - 16 - - 17 - - 18 - - 19 - - 20 - - 21 - - 22 - - 23 - - 24 - - 25 - - 26 - - 27 - - 28 - - 29 - - 30 -

More information

C 프로그래밍 언어 입문 C 프로그래밍 언어 입문 김명호저 숭실대학교 출판국 머리말..... C, C++, Java, Fortran, Python, Ruby,.. C. C 1972. 40 C.. C. 1999 C99. C99. C. C. C., kmh ssu.ac.kr.. ,. 2013 12 Contents 1장 프로그래밍 시작 1.1 C 10 1.2 12

More information

K7VT2_QIG_v3

K7VT2_QIG_v3 1......... 2 3..\ 4 5 [R] : Enter Raid setup utility 6 Press[A]keytocreateRAID RAID Type: JBOD RAID 0 RAID 1: 2 7 " RAID 0 Auto Create Manual Create: 2 RAID 0 Block Size: 16K 32K

More information

<4D F736F F F696E74202D20B8AEB4AABDBA20BFC0B7F920C3B3B8AEC7CFB1E22E BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D20B8AEB4AABDBA20BFC0B7F920C3B3B8AEC7CFB1E22E BC8A3C8AF20B8F0B5E55D> 리눅스 오류처리하기 2007. 11. 28 안효창 라이브러리함수의오류번호얻기 errno 변수기능오류번호를저장한다. 기본형 extern int errno; 헤더파일 라이브러리함수호출에실패했을때함수예 정수값을반환하는함수 -1 반환 open 함수 포인터를반환하는함수 NULL 반환 fopen 함수 2 유닉스 / 리눅스 라이브러리함수의오류번호얻기 19-1

More information

DE1-SoC Board

DE1-SoC Board 실습 1 개발환경 DE1-SoC Board Design Tools - Installation Download & Install Quartus Prime Lite Edition http://www.altera.com/ Quartus Prime (includes Nios II EDS) Nios II Embedded Design Suite (EDS) is automatically

More information

Chapter #01 Subject

Chapter #01  Subject Device Driver March 24, 2004 Kim, ki-hyeon 목차 1. 인터럽트처리복습 1. 인터럽트복습 입력검출방법 인터럽트방식, 폴링 (polling) 방식 인터럽트서비스등록함수 ( 커널에등록 ) int request_irq(unsigned int irq, void(*handler)(int,void*,struct pt_regs*), unsigned

More information

Page 2 of 6 Here are the rules for conjugating Whether (or not) and If when using a Descriptive Verb. The only difference here from Action Verbs is wh

Page 2 of 6 Here are the rules for conjugating Whether (or not) and If when using a Descriptive Verb. The only difference here from Action Verbs is wh Page 1 of 6 Learn Korean Ep. 13: Whether (or not) and If Let s go over how to say Whether and If. An example in English would be I don t know whether he ll be there, or I don t know if he ll be there.

More information

step 1-1

step 1-1 Written by Dr. In Ku Kim-Marshall STEP BY STEP Korean 1 through 15 Action Verbs Table of Contents Unit 1 The Korean Alphabet, hangeul Unit 2 Korean Sentences with 15 Action Verbs Introduction Review Exercises

More information

제11장 프로세스와 쓰레드

제11장 프로세스와 쓰레드 제9장자바쓰레드 9.1 Thread 기초 (1/5) 프로그램 명령어들의연속 (a sequence of instruction) 프로세스 / Thread 실행중인프로그램 (program in execution) 프로세스생성과실행을위한함수들 자바 Thread 2 9.1 Thread 기초 (2/5) 프로세스단위작업의문제점 프로세스생성시오버헤드 컨텍스트스위치오버헤드

More information

chapter4

chapter4 Basic Netw rk 1. ก ก ก 2. 3. ก ก 4. ก 2 1. 2. 3. 4. ก 5. ก 6. ก ก 7. ก 3 ก ก ก ก (Mainframe) ก ก ก ก (Terminal) ก ก ก ก ก ก ก ก 4 ก (Dumb Terminal) ก ก ก ก Mainframe ก CPU ก ก ก ก 5 ก ก ก ก ก ก ก ก ก ก

More information

MAX+plus II Getting Started - 무작정따라하기

MAX+plus II Getting Started - 무작정따라하기 무작정 따라하기 2001 10 4 / Version 20-2 0 MAX+plus II Digital, Schematic Capture MAX+plus II, IC, CPLD FPGA (Logic) ALTERA PLD FLEX10K Series EPF10K10QC208-4 MAX+plus II Project, Schematic, Design Compilation,

More information

C++-¿Ïº®Çؼ³10Àå

C++-¿Ïº®Çؼ³10Àå C C++. (preprocessor directives), C C++ C/C++... C++, C. C++ C. C C++. C,, C++, C++., C++.,.. #define #elif #else #error #if #itdef #ifndef #include #line #pragma #undef #.,.,. #include #include

More information

휠세미나3 ver0.4

휠세미나3 ver0.4 andromeda@sparcs:/$ ls -al dev/sda* brw-rw---- 1 root disk 8, 0 2014-06-09 18:43 dev/sda brw-rw---- 1 root disk 8, 1 2014-06-09 18:43 dev/sda1 brw-rw---- 1 root disk 8, 2 2014-06-09 18:43 dev/sda2 andromeda@sparcs:/$

More information

untitled

untitled - -, (insert) (delete) - - (insert) (delete) (top ) - - (insert) (rear) (delete) (front) A A B top A B C top push(a) push(b) push(c) A B top pop() top A B D push(d) top #define MAX_STACK_SIZE 100 int

More information

歯9장.PDF

歯9장.PDF 9 Hello!! C printf() scanf() getchar() putchar() gets() puts() fopen() fclose() fprintf() fscant() fgetc() fputs() fgets() gputs() fread() fwrite() fseek() ftell() I/O 2 (stream) C (text stream) : `/n'

More information

슬라이드 1

슬라이드 1 -Part3- 제 4 장동적메모리할당과가변인 자 학습목차 4.1 동적메모리할당 4.1 동적메모리할당 4.1 동적메모리할당 배울내용 1 프로세스의메모리공간 2 동적메모리할당의필요성 4.1 동적메모리할당 (1/6) 프로세스의메모리구조 코드영역 : 프로그램실행코드, 함수들이저장되는영역 스택영역 : 매개변수, 지역변수, 중괄호 ( 블록 ) 내부에정의된변수들이저장되는영역

More information

목차 BUG offline replicator 에서유효하지않은로그를읽을경우비정상종료할수있다... 3 BUG 각 partition 이서로다른 tablespace 를가지고, column type 이 CLOB 이며, 해당 table 을 truncate

목차 BUG offline replicator 에서유효하지않은로그를읽을경우비정상종료할수있다... 3 BUG 각 partition 이서로다른 tablespace 를가지고, column type 이 CLOB 이며, 해당 table 을 truncate ALTIBASE HDB 6.1.1.5.6 Patch Notes 목차 BUG-39240 offline replicator 에서유효하지않은로그를읽을경우비정상종료할수있다... 3 BUG-41443 각 partition 이서로다른 tablespace 를가지고, column type 이 CLOB 이며, 해당 table 을 truncate 한뒤, hash partition

More information

example code are examined in this stage The low pressure pressurizer reactor trip module of the Plant Protection System was programmed as subject for

example code are examined in this stage The low pressure pressurizer reactor trip module of the Plant Protection System was programmed as subject for 2003 Development of the Software Generation Method using Model Driven Software Engineering Tool,,,,, Hoon-Seon Chang, Jae-Cheon Jung, Jae-Hack Kim Hee-Hwan Han, Do-Yeon Kim, Young-Woo Chang Wang Sik, Moon

More information

/chroot/lib/ /chroot/etc/

/chroot/lib/ /chroot/etc/ 구축 환경 VirtualBox - Fedora 15 (kernel : 2.6.40.4-5.fc15.i686.PAE) 작동 원리 chroot유저 ssh 접속 -> 접속유저의 홈디렉토리 밑.ssh의 rc 파일 실행 -> daemonstart실행 -> daemon 작동 -> 접속 유저만의 Jail 디렉토리 생성 -> 접속 유저의.bashrc 의 chroot 명령어

More information

ORANGE FOR ORACLE V4.0 INSTALLATION GUIDE (Online Upgrade) ORANGE CONFIGURATION ADMIN O

ORANGE FOR ORACLE V4.0 INSTALLATION GUIDE (Online Upgrade) ORANGE CONFIGURATION ADMIN O Orange for ORACLE V4.0 Installation Guide ORANGE FOR ORACLE V4.0 INSTALLATION GUIDE...1 1....2 1.1...2 1.2...2 1.2.1...2 1.2.2 (Online Upgrade)...11 1.3 ORANGE CONFIGURATION ADMIN...12 1.3.1 Orange Configuration

More information

지능정보연구제 16 권제 1 호 2010 년 3 월 (pp.71~92),.,.,., Support Vector Machines,,., KOSPI200.,. * 지능정보연구제 16 권제 1 호 2010 년 3 월

지능정보연구제 16 권제 1 호 2010 년 3 월 (pp.71~92),.,.,., Support Vector Machines,,., KOSPI200.,. * 지능정보연구제 16 권제 1 호 2010 년 3 월 지능정보연구제 16 권제 1 호 2010 년 3 월 (pp.71~92),.,.,., Support Vector Machines,,., 2004 5 2009 12 KOSPI200.,. * 2009. 지능정보연구제 16 권제 1 호 2010 년 3 월 김선웅 안현철 社 1), 28 1, 2009, 4. 1. 지능정보연구제 16 권제 1 호 2010 년 3 월 Support

More information

Poison null byte Excuse the ads! We need some help to keep our site up. List 1 Conditions 2 Exploit plan 2.1 chunksize(p)!= prev_size (next_chunk(p) 3

Poison null byte Excuse the ads! We need some help to keep our site up. List 1 Conditions 2 Exploit plan 2.1 chunksize(p)!= prev_size (next_chunk(p) 3 Poison null byte Excuse the ads! We need some help to keep our site up. List 1 Conditions 2 Exploit plan 2.1 chunksize(p)!= prev_size (next_chunk(p) 3 Example 3.1 Files 3.2 Source code 3.3 Exploit flow

More information

4 5 4. Hi-MO 애프터케어 시스템 편 5. 오비맥주 카스 카스 후레쉬 테이블 맥주는 천연식품이다 편 처음 스타일 그대로, 부탁 케어~ Hi-MO 애프터케어 시스템 지속적인 모발 관리로 끝까지 스타일이 유지되도록 독보적이다! 근데 그거 아세요? 맥주도 인공첨가물이

4 5 4. Hi-MO 애프터케어 시스템 편 5. 오비맥주 카스 카스 후레쉬 테이블 맥주는 천연식품이다 편 처음 스타일 그대로, 부탁 케어~ Hi-MO 애프터케어 시스템 지속적인 모발 관리로 끝까지 스타일이 유지되도록 독보적이다! 근데 그거 아세요? 맥주도 인공첨가물이 1 2 On-air 3 1. 이베이코리아 G마켓 용평리조트 슈퍼브랜드딜 편 2. 아모레퍼시픽 헤라 루즈 홀릭 리퀴드 편 인쇄 광고 올해도 겨울이 왔어요. 당신에게 꼭 해주고 싶은 말이 있어요. G마켓에선 용평리조트 스페셜 패키지가 2만 6900원! 역시 G마켓이죠? G마켓과 함께하는 용평리조트 스페셜 패키지. G마켓의 슈퍼브랜드딜은 계속된다. 모바일 쇼핑 히어로

More information

10.

10. 10. 10.1 10.2 Library Routine: void perror (char* str) perror( ) str Error 0 10.3 10.3 int fd; /* */ fd = open (filename, ) /*, */ if (fd = = -1) { /* */ } fcnt1 (fd, ); /* */ read (fd, ); /* */ write

More information

chap 5: Trees

chap 5: Trees 5. Threaded Binary Tree 기본개념 n 개의노드를갖는이진트리에는 2n 개의링크가존재 2n 개의링크중에 n + 1 개의링크값은 null Null 링크를다른노드에대한포인터로대체 Threads Thread 의이용 ptr left_child = NULL 일경우, ptr left_child 를 ptr 의 inorder predecessor 를가리키도록변경

More information

Microsoft PowerPoint - StallingsOS6e-Chap05.pptx

Microsoft PowerPoint - StallingsOS6e-Chap05.pptx 5 장병행성 : 상호배제와동기화 5 장의강의목표 병행성 (concurrency) 의원리와주요용어를이해한다. 경쟁상태 (race condition) 의문제점에대해이해한다. 상호배제 (mutual exclusion), 교착상태 (deadlock), 기아상태 (starvation) 의 3 가지제어문제를이해한다. 상호배제를보장하기위한하드웨어적접근방법을이해한다. 세마포어를이용한상호배제기법을이해한다.

More information

61 62 63 64 234 235 p r i n t f ( % 5 d :, i+1); g e t s ( s t u d e n t _ n a m e [ i ] ) ; if (student_name[i][0] == \ 0 ) i = MAX; p r i n t f (\ n :\ n ); 6 1 for (i = 0; student_name[i][0]!= \ 0&&

More information

0. 표지에이름과학번을적으시오. (6) 1. 변수 x, y 가 integer type 이라가정하고다음빈칸에 x 와 y 의계산결과값을적으시오. (5) x = (3 + 7) * 6; x = 60 x = (12 + 6) / 2 * 3; x = 27 x = 3 * (8 / 4

0. 표지에이름과학번을적으시오. (6) 1. 변수 x, y 가 integer type 이라가정하고다음빈칸에 x 와 y 의계산결과값을적으시오. (5) x = (3 + 7) * 6; x = 60 x = (12 + 6) / 2 * 3; x = 27 x = 3 * (8 / 4 Introduction to software design 2012-1 Final 2012.06.13 16:00-18:00 Student ID: Name: - 1 - 0. 표지에이름과학번을적으시오. (6) 1. 변수 x, y 가 integer type 이라가정하고다음빈칸에 x 와 y 의계산결과값을적으시오. (5) x = (3 + 7) * 6; x = 60 x

More information

3. 다음장에나오는 sigprocmask 함수의설명을참고하여다음프로그램의출력물과그출력물이화면이표시되는시점을예측하세요. ( 힌트 : 각줄이표시되는시점은다음 4 가지중하나. (1) 프로그램수행직후, (2) kill 명령실행직후, (3) 15 #include <signal.

3. 다음장에나오는 sigprocmask 함수의설명을참고하여다음프로그램의출력물과그출력물이화면이표시되는시점을예측하세요. ( 힌트 : 각줄이표시되는시점은다음 4 가지중하나. (1) 프로그램수행직후, (2) kill 명령실행직후, (3) 15 #include <signal. 학번 : 이름 : 1. 다음가정하에서아래프로그램의출력물을예측하세요. 가정 : 부모프로세스의 process id=20100, 자식프로세스의 process id=20101. int glob = 31; /* external variable in initialized data */ char buf[] = "a write to stdout\n"; int main(void)

More information

<30362E20C6EDC1FD2DB0EDBFB5B4EBB4D420BCF6C1A42E687770>

<30362E20C6EDC1FD2DB0EDBFB5B4EBB4D420BCF6C1A42E687770> 327 Journal of The Korea Institute of Information Security & Cryptology ISSN 1598-3986(Print) VOL.24, NO.2, Apr. 2014 ISSN 2288-2715(Online) http://dx.doi.org/10.13089/jkiisc.2014.24.2.327 개인정보 DB 암호화

More information

Solaris Express Developer Edition

Solaris Express Developer Edition Solaris Express Developer Edition : 2008 1 Solaris TM Express Developer Edition Solaris OS. Sun / Solaris, Java, Web 2.0,,. Developer Solaris Express Developer Edition System Requirements. 768MB. SPARC

More information

No Slide Title

No Slide Title Copyright, 2001 Multimedia Lab., CH 3. COM object (In-process server) Eun-sung Lee twoss@mmlab.net Multimedia Lab. Dept. of Electrical and Computer Eng. University of Seoul Seoul, Korea 0. Contents 1.

More information

본문01

본문01 Ⅱ 논술 지도의 방법과 실제 2. 읽기에서 논술까지 의 개발 배경 읽기에서 논술까지 자료집 개발의 본래 목적은 초 중 고교 학교 평가에서 서술형 평가 비중이 2005 학년도 30%, 2006학년도 40%, 2007학년도 50%로 확대 되고, 2008학년도부터 대학 입시에서 논술 비중이 커지면서 논술 교육은 학교가 책임진다. 는 풍토 조성으로 공교육의 신뢰성과

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 KeyPad Device Control - Device driver Jo, Heeseung HBE-SM5-S4210 에는 16 개의 Tack Switch 를사용하여 4 행 4 열의 Keypad 가장착 4x4 Keypad 2 KeyPad 를제어하기위하여 FPGA 내부에 KeyPad controller 가구현 KeyPad controller 16bit 로구성된

More information

Chapter_06

Chapter_06 프로그래밍 1 1 Chapter 6. Functions and Program Structure April, 2016 Dept. of software Dankook University http://embedded.dankook.ac.kr/~baeksj 이장의강의목표 2 문자의입력방법을이해한다. 중첩된 if문을이해한다. while 반복문의사용법을익힌다. do 반복문의사용법을익힌다.

More information

Microsoft Word - FunctionCall

Microsoft Word - FunctionCall Function all Mechanism /* Simple Program */ #define get_int() IN KEYOARD #define put_int(val) LD A val \ OUT MONITOR int add_two(int a, int b) { int tmp; tmp = a+b; return tmp; } local auto variable stack

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 @ Lesson 2... ( ). ( ). @ vs. logic data method variable behavior attribute method field Flow (Type), ( ) member @ () : C program Method A ( ) Method B ( ) Method C () program : Java, C++, C# data @ Program

More information

본 강의에 들어가기 전

본 강의에 들어가기 전 C 기초특강 종합과제 과제내용 구조체를이용하여교과목이름과코드를파일로부터입력받아관리 구조체를이용하여학생들의이름, 학번과이수한교과목의코드와점수를파일로부터입력 학생개인별총점, 평균계산 교과목별이수학생수, 총점및평균을계산 결과를파일에저장하는프로그램을작성 2 Makefile OBJS = score_main.o score_input.o score_calc.o score_print.o

More information

The Self-Managing Database : Automatic Health Monitoring and Alerting

The Self-Managing Database : Automatic Health Monitoring and Alerting The Self-Managing Database : Automatic Health Monitoring and Alerting Agenda Oracle 10g Enterpirse Manager Oracle 10g 3 rd Party PL/SQL API Summary (Self-Managing Database) ? 6% 6% 12% 55% 6% Source: IOUG

More information

ABC 11장

ABC 11장 12 장고급응용 0 수행중인프로그램 프로세스 모든프로세스는유일한프로세스식별번호 (PID) 를가짐 유닉스에서는 ps 명령을사용하여프로세스목록을볼수있음 12-1 프로세스 $ ps -aux USER PID %CPU %MEM SZ RSS TT STAT START TIME COMMAND blufox 17725 34.0 1.6 146 105 i2 R 15:13 0:00

More information

Microsoft PowerPoint - StallingsOS6e-Chap06.ppt [호환 모드]

Microsoft PowerPoint - StallingsOS6e-Chap06.ppt [호환 모드] 6 장병행성 : 교착상태와기아 6 장의강의목표 교착상태 (deadlock) 의원리를이해한다. 교착상태에자원할당그래프가어떻게이용되는지이해한다. 교착상태가발생하기위한필요. 충분조건을이해한다. 교착상태예방기법들을이해한다. 교착상태회피기법들을이해한다. 교착상태의발견과복구기법들을이해한다. 식사하는철학자문제를이해하고해결방법을이해한다. UNIX, LINUX, Solaris,

More information

Remote UI Guide

Remote UI Guide Remote UI KOR Remote UI Remote UI PDF Adobe Reader/Adobe Acrobat Reader. Adobe Reader/Adobe Acrobat Reader Adobe Systems Incorporated.. Canon. Remote UI GIF Adobe Systems Incorporated Photoshop. ..........................................................

More information

프로그램을 학교 등지에서 조금이라도 배운 사람들을 위한 프로그래밍 노트 입니다. 저 역시 그 사람들 중 하나 입니다. 중고등학교 시절 학교 도서관, 새로 생긴 시립 도서관 등을 다니며 책을 보 고 정리하며 어느정도 독학으르 공부하긴 했지만, 자주 안하다 보면 금방 잊어

프로그램을 학교 등지에서 조금이라도 배운 사람들을 위한 프로그래밍 노트 입니다. 저 역시 그 사람들 중 하나 입니다. 중고등학교 시절 학교 도서관, 새로 생긴 시립 도서관 등을 다니며 책을 보 고 정리하며 어느정도 독학으르 공부하긴 했지만, 자주 안하다 보면 금방 잊어 개나리 연구소 C 언어 노트 (tyback.egloos.com) 프로그램을 학교 등지에서 조금이라도 배운 사람들을 위한 프로그래밍 노트 입니다. 저 역시 그 사람들 중 하나 입니다. 중고등학교 시절 학교 도서관, 새로 생긴 시립 도서관 등을 다니며 책을 보 고 정리하며 어느정도 독학으르 공부하긴 했지만, 자주 안하다 보면 금방 잊어먹고 하더라구요. 그래서,

More information

` Companies need to play various roles as the network of supply chain gradually expands. Companies are required to form a supply chain with outsourcing or partnerships since a company can not

More information

Microsoft PowerPoint - chap10-함수의활용.pptx

Microsoft PowerPoint - chap10-함수의활용.pptx #include int main(void) { int num; printf( Please enter an integer: "); scanf("%d", &num); if ( num < 0 ) printf("is negative.\n"); printf("num = %d\n", num); return 0; } 1 학습목표 중 값에 의한 전달 방법과

More information

Microsoft PowerPoint - chap13-입출력라이브러리.pptx

Microsoft PowerPoint - chap13-입출력라이브러리.pptx #include int main(void) int num; printf( Please enter an integer: "); scanf("%d", &num); if ( num < 0 ) printf("is negative.\n"); printf("num = %d\n", num); return 0; 1 학습목표 스트림의 기본 개념을 알아보고,

More information

#Ȳ¿ë¼®

#Ȳ¿ë¼® http://www.kbc.go.kr/ A B yk u δ = 2u k 1 = yk u = 0. 659 2nu k = 1 k k 1 n yk k Abstract Web Repertoire and Concentration Rate : Analysing Web Traffic Data Yong - Suk Hwang (Research

More information

김기남_ATDC2016_160620_[키노트].key

김기남_ATDC2016_160620_[키노트].key metatron Enterprise Big Data SKT Metatron/Big Data Big Data Big Data... metatron Ready to Enterprise Big Data Big Data Big Data Big Data?? Data Raw. CRM SCM MES TCO Data & Store & Processing Computational

More information

좀비프로세스 2

좀비프로세스 2 Signal & Inter-Process Communication Department of Computer Engineering Kyung Hee University. Choong Seon Hong 1 좀비프로세스 2 좀비프로세스 (zombie process) 좀비프로세스란프로세스종료후메모리상에서사라지지않는프로세스 좀비프로세스의생성이유. 자식프로세스는부모프로세스에게실행결과에대한값을반환해야한다.

More information

歯3이화진

歯3이화진 http://www.kbc.go.kr/ Abstract Terrestrial Broadcasters Strategies in the Age of Digital Broadcasting Wha-Jin Lee The purpose of this research is firstly to investigate the

More information

4. #include <stdio.h> #include <stdlib.h> int main() { functiona(); } void functiona() { printf("hihi\n"); } warning: conflicting types for functiona

4. #include <stdio.h> #include <stdlib.h> int main() { functiona(); } void functiona() { printf(hihi\n); } warning: conflicting types for functiona 이름 : 학번 : A. True or False: 각각항목마다 True 인지 False 인지적으세요. 1. (Python:) randint 함수를사용하려면, random 모듈을 import 해야한다. 2. (Python:) '' (single quote) 는한글자를표현할때, (double quote) 는문자열을표현할때사용한다. B. 다음에러를수정하는방법을적으세요.

More information

Embeddedsystem(8).PDF

Embeddedsystem(8).PDF insmod init_module() register_blkdev() blk_init_queue() blk_dev[] request() default queue blkdevs[] block_device_ops rmmod cleanup_module() unregister_blkdev() blk_cleanup_queue() static struct { const

More information

04-다시_고속철도61~80p

04-다시_고속철도61~80p Approach for Value Improvement to Increase High-speed Railway Speed An effective way to develop a highly competitive system is to create a new market place that can create new values. Creating tools and

More information

강의지침서 작성 양식

강의지침서 작성 양식 정보화사회와 법 강의지침서 1. 교과목 정보 교과목명 학점 이론 시간 실습 학점(등급제, P/NP) 비고 (예:팀티칭) 국문 정보화사회와 법 영문 Information Society and Law 3 3 등급제 구분 대학 및 기관 학부(과) 전공 성명 작성 책임교수 법학전문대학원 법학과 최우용 2. 교과목 개요 구분 교과목 개요 국문 - 정보의 디지털화와 PC,

More information

API 매뉴얼

API 매뉴얼 PCI-DIO12 API Programming (Rev 1.0) Windows, Windows2000, Windows NT and Windows XP are trademarks of Microsoft. We acknowledge that the trademarks or service names of all other organizations mentioned

More information

Microsoft PowerPoint os5.ppt

Microsoft PowerPoint os5.ppt 5 장스레드 (Threads) 프로세스 = 자원 + PC 스레드 : 새 PC (a thread of control) 로같은 address space 를실행하는 fork 와유사 스레드 (Threads) 개요 ~ 경량프로세스 (LWP; lightweight process) = 스레드» CPU 를이용하는기본단위» thread ID, PC, 레지스터세트, 스택영역을가짐»

More information

Sena Technologies, Inc. HelloDevice Super 1.1.0

Sena Technologies, Inc. HelloDevice Super 1.1.0 HelloDevice Super 110 Copyright 1998-2005, All rights reserved HelloDevice 210 ()137-130 Tel: (02) 573-5422 Fax: (02) 573-7710 E-Mail: support@senacom Website: http://wwwsenacom Revision history Revision

More information

03장.스택.key

03장.스택.key ---------------- DATA STRUCTURES USING C ---------------- 03CHAPTER 1 ? (stack): (LIFO:Last-In First-Out) 2 : top : ( index -1 ),,, 3 : ( ) ( ) -> ->. ->.... 4 Stack ADT : (LIFO) : init():. is_empty():

More information

09김정식.PDF

09김정식.PDF 00-09 2000. 12 ,,,,.,.,.,,,,,,.,,..... . 1 1 7 2 9 1. 9 2. 13 3. 14 3 16 1. 16 2. 21 3. 39 4 43 1. 43 2. 52 3. 56 4. 66 5. 74 5 78 1. 78 2. 80 3. 86 6 88 90 Ex e cu t iv e Su m m a r y 92 < 3-1> 22 < 3-2>

More information

APOGEE Insight_KR_Base_3P11

APOGEE Insight_KR_Base_3P11 Technical Specification Sheet Document No. 149-332P25 September, 2010 Insight 3.11 Base Workstation 그림 1. Insight Base 메인메뉴 Insight Base Insight Insight Base, Insight Base Insight Base Insight Windows

More information

11장 포인터

11장 포인터 Dynamic Memory and Linked List 1 동적할당메모리의개념 프로그램이메모리를할당받는방법 정적 (static) 동적 (dynamic) 정적메모리할당 프로그램이시작되기전에미리정해진크기의메모리를할당받는것 메모리의크기는프로그램이시작하기전에결정 int i, j; int buffer[80]; char name[] = data structure"; 처음에결정된크기보다더큰입력이들어온다면처리하지못함

More information

Microsoft PowerPoint os5.ppt [호환 모드]

Microsoft PowerPoint os5.ppt [호환 모드] 5 장스레드 (Threads) 프로세스 = 자원 + PC 스레드 : 새 PC (a thread of control) 로같은 address space 를실행하는 fork 와유사 스레드 (Threads) 개요 경량프로세스 (LWP; lightweight process) = 스레드» CPU 를이용하는기본단위» thread ID, PC, 레지스터세트, 스택영역을가짐»

More information

C# Programming Guide - Types

C# Programming Guide - Types C# Programming Guide - Types 최도경 lifeisforu@wemade.com 이문서는 MSDN 의 Types 를요약하고보충한것입니다. http://msdn.microsoft.com/enus/library/ms173104(v=vs.100).aspx Types, Variables, and Values C# 은 type 에민감한언어이다. 모든

More information

- 이 문서는 삼성전자의 기술 자산으로 승인자만이 사용할 수 있습니다 Part Picture Description 5. R emove the memory by pushing the fixed-tap out and Remove the WLAN Antenna. 6. INS

- 이 문서는 삼성전자의 기술 자산으로 승인자만이 사용할 수 있습니다 Part Picture Description 5. R emove the memory by pushing the fixed-tap out and Remove the WLAN Antenna. 6. INS [Caution] Attention to red sentence 3-1. Disassembly and Reassembly R520/ 1 2 1 1. As shown in picture, adhere Knob to the end closely into the arrow direction(1), then push the battery up (2). 2. Picture

More information

00 SPH-V6900_....

00 SPH-V6900_.... SPH-V6900 사용설명서 사용전에 안전을 위한 경고 및 주의사항을 반드시 읽고 바르게 사용해 주세요. 사용설명서의 화면과 그림은 실물과 다를 수 있습니다. 사용설명서의 내용은 휴대전화의 소프트웨어 버전 또는 KTF 사업자의 사정에 따라 다를 수 있으며, 사용자에게 통보없이 일부 변경될 수 있습니다. 휴대전화의 소프트웨어는 사용자가 최신 버전으로 업그레이드

More information

PRO1_09E [읽기 전용]

PRO1_09E [읽기 전용] Siemens AG 1999 All rights reserved File: PRO1_09E1 Information and - ( ) 2 3 4 5 Monitor/Modify Variables" 6 7 8 9 10 11 CPU 12 Stop 13 (Forcing) 14 (1) 15 (2) 16 : 17 : Stop 18 : 19 : (Forcing) 20 :

More information

Stage 2 First Phonics

Stage 2 First Phonics ORT Stage 2 First Phonics The Big Egg What could the big egg be? What are the characters doing? What do you think the story will be about? (큰 달걀은 무엇일까요? 등장인물들은 지금 무엇을 하고 있는 걸까요? 책은 어떤 내용일 것 같나요?) 대해 칭찬해

More information

<32B1B3BDC32E687770>

<32B1B3BDC32E687770> 008년도 상반기 제회 한 국 어 능 력 시 험 The th Test of Proficiency in Korean 일반 한국어(S-TOPIK 중급(Intermediate A 교시 이해 ( 듣기, 읽기 수험번호(Registration No. 이 름 (Name 한국어(Korean 영 어(English 유 의 사 항 Information. 시험 시작 지시가 있을

More information

4 CD Construct Special Model VI 2 nd Order Model VI 2 Note: Hands-on 1, 2 RC 1 RLC mass-spring-damper 2 2 ζ ω n (rad/sec) 2 ( ζ < 1), 1 (ζ = 1), ( ) 1

4 CD Construct Special Model VI 2 nd Order Model VI 2 Note: Hands-on 1, 2 RC 1 RLC mass-spring-damper 2 2 ζ ω n (rad/sec) 2 ( ζ < 1), 1 (ζ = 1), ( ) 1 : LabVIEW Control Design, Simulation, & System Identification LabVIEW Control Design Toolkit, Simulation Module, System Identification Toolkit 2 (RLC Spring-Mass-Damper) Control Design toolkit LabVIEW

More information

Microsoft PowerPoint - chap6 [호환 모드]

Microsoft PowerPoint - chap6 [호환 모드] 제 6 장프로세스 (Process) 숙대창병모 1 내용 프로세스시작 / 종료 명령중인수 / 환경변수 메모리배치 / 할당 비지역점프 숙대창병모 2 프로세스시작 / 종료 숙대창병모 3 Process Start Kernel exec system call user process Cstart-up routine call return int main(int argc,

More information

Microsoft Word - ExecutionStack

Microsoft Word - ExecutionStack Lecture 15: LM code from high level language /* Simple Program */ external int get_int(); external void put_int(); int sum; clear_sum() { sum=0; int step=2; main() { register int i; static int count; clear_sum();

More information