Chapter 05 Multithread q Goal IT COOKBOOK Understanding
Chapter 05. Multithread
q Goal IT COOKBOOK • Understanding basic multithread concept • Coding TCP server multithread • Learning thread synchronization methods -1 -
q Process and thread (1/2) IT COOKBOOK • Terms – process • one executing instance of a “program” • It’s separate from other instances • Contains code (text), data, stack, heap – thread • a light-weighted process – primary thread • Thread that is executed in main() or Win. Main() – context switch • occurs when the kernel switches from executing one thread to executing another. • The kernel saves the context of the currently running thread and resumes the context of the next thread that is scheduled to run. -2 -
q. Threads: Lightweight Processes Environment (resource) IT COOKBOOK execution • (a) Three processes each with one thread • (b) One process with three threads -3 -
q Process and thread (2/2) IT COOKBOOK • Context switching process ① ② CPU thread① register CPU thread② register ① ② thread① register CPU thread② register -4 -
q thread creation and termination (1/6) • Elements for thread creation – Starting address of thread function – Stack region for thread function execution -5 - IT COOKBOOK
q thread creation and termination (2/6) IT COOKBOOK • address space of process thread ①, ② – Two functions – Three threads Primary thread f() {. . . } main() {. . . } code Execution stack of Primary thread Execution stack of Thread ① Execution stack of Thread ② -6 -
q thread creation and termination (3/6) IT COOKBOOK • Create. Thread() function – Return thread handle after thread creation HANDLE Create. Thread ( LPSECURITY_ATTRIBUTES lp. Thread. Attributes, // NULL SIZE_T dw. Stack. Size, // 0 LPTHREAD_START_ROUTINE lp. Start. Address, //thread function LPVOID lp. Parameter, // thread function argument DWORD dw. Creation. Flags, // 0 or CREATE_SUSPENDED LPDWORD lp. Thread. Id // thread ID ); success: thread handle, fail: NULL -7 -
q thread creation and termination (4/6) • Thread function definition DWORD WINAPI Thread. Proc (LPVOID lp. Parameter) {. . . } -8 - IT COOKBOOK
q thread creation and termination (5/6) IT COOKBOOK • Ways to terminate thread ① when thread function finish ② call Exit. Thread() function in thread function ③ call Terminate. Thread() function ④ all threads are terminated when primay thread is terminated • Ex. Thread 1. cpp -9 -
q thread creation and termination (6/6) IT COOKBOOK • Thread termination functions void Exit. Thread ( DWORD dw. Exit. Code // exit code ); BOOL Terminate. Thread ( HANDLE h. Thread, // thread handle to terminate DWORD dw. Exit. Code // exit code ); success: some value except 0, fail: 0 - 10 -
q thread handling – priority (1/5) IT COOKBOOK • Terms – thread scheduling • Scheduling CPU time to each thread – priority class • Process property, • All threads in a process have same priority class – priority level • Thread property, • A thread in a process may have different priority – base priority • Combination of priority class and priority level • Used in thread scheduling - 11 -
q thread handling – priority (2/5) IT COOKBOOK • Priority class – – – REALTIME_PRIORITY_CLASS HIGH_PRIORITY_CLASS ABOVE_NORMAL_PRIORITY_CLASS BELOW_NORMAL_PRIORITY_CLASS IDLE_PRIORITY_CLASS - 12 -
q thread handling – priority (3/5) IT COOKBOOK • Priority level – – – – THREAD_PRIORITY_TIME_CRITICAL THREAD_PRIORITY_HIGHEST THREAD_PRIORITY_ABOVE_NORMAL THREAD_PRIORITY_BELOW_NORMAL THREAD_PRIORITY_LOWEST THREAD_PRIORITY_IDLE - 13 -
q thread handling – priority (4/5) IT COOKBOOK • Priority based thread scheduling (low) priority (high) . . . Three threads in turn thread scheduler CPU - 14 -
q thread handling – priority (5/5) IT COOKBOOK • Priority level handling function BOOL Set. Thread. Priority ( HANDLE h. Thread, // thread handle int n. Priority // priority level value ); success: some value except 0, fail: 0 int Get. Thread. Priority ( HANDLE h. Thread // thread handle ); success: priority level value, fail: THREAD_PRIORITY_ERROR_RETURN • Ex. Thread 2. cpp - 15 -
q thread handling – waiting thread termination (1/4) IT COOKBOOK • Wait. For. Single. Object() function – Waiting for the termination of single thread DWORD Wait. For. Single. Object ( HANDLE h. Handle, DWORD dw. Milliseconds ); success: WAIT_OBJECT_0 or WAIT_TIMEOUT, fail: WAIT_FAILED • Wait. For. Single. Object() function example HANDLE h. Thread = Create. Thread(. . . ); Wait. For. Single. Object(h. Thread, INFINITE); - 16 -
q thread handling – waiting thread termination (2/4) IT COOKBOOK • Wait. For. Multiple. Objects() function – Waiting for the termination of two threads or more DWORD Wait. For. Multiple. Objects ( DWORD n. Count, const HANDLE* lp. Handles, BOOL b. Wait. All, DWORD dw. Milliseconds ); success: WAIT_OBJECT_0 ~ WAIT_OBJECT_0 + n. Count-1 or WAIT_TIMEOUT, fail: WAIT_FAILED - 17 -
q thread handling – waiting thread termination (3/4) IT COOKBOOK • Wait. For. Multiple. Objects() function example ① // waiting for the termination of all threads HANDLE h. Thread[2]; HANDLE h. Thread[0] = Create. Thread(. . . ); HANDLE h. Thread[1] = Create. Thread(. . . ); Wait. For. Multiple. Objects(2, h. Thread, TRUE, INFINITE); - 18 -
q thread handling – waiting thread termination (4/4) IT COOKBOOK • Wait. For. Multiple. Objects() function example ② // waiting for one thread termination of two threads HANDLE h. Thread[2]; HANDLE h. Thread[0] = Create. Thread(. . . ); HANDLE h. Thread[1] = Create. Thread(. . . ); DWORD retval = Wait. For. Multiple. Objects(2, h. Thread, FALSE, INFINITE); switch(retval){ case WAIT_OBJECT_0: // h. Thread[0] termination break; case WAIT_OBJECT_0+1: // h. Thread[1] termination break; case WAIT_FAILED: // error break; } - 19 -
q thread handling – suspend and resume (1/2) IT COOKBOOK • Suspend function ① DWORD Suspend. Thread ( HANDLE h. Thread // thread handle ); success: num of suspend, fail: -1 • Resume function DWORD Resume. Thread ( HANDLE h. Thread // thread handle ); success: num of suspend, fail: -1 - 20 -
q thread handling – suspend and resume (2/2) • Sleep function ② – Thread stop and wait for the defind time void Sleep ( DWORD dw. Milliseconds // millisecond(ms) ); • Ex. Thread 3. cpp - 21 - IT COOKBOOK
q Multithread TCP Server (1/3) IT COOKBOOK • Basic structure DWORD WINAPI Process. Client(LPVOID arg) { // socket transfer ③ SOCKET client_sock = (SOCKET)arg; // getting client information ④ addrlen = sizeof(clientaddr); getpeername(client_sock, (SOCKADDR *)&clientaddr, &addrlen); // data comm. with client ⑤ while(1){. . . } closesocket(client_sock); return 0; } - 22 -
q Multithread TCP Server (2/3) IT COOKBOOK • Basic structure (cont’d) int main(int argc, char* argv[]) {. . . while(1){ // accept client connection ① client_sock = accept(listen_sock, . . . ); . . . // thread creation ② Create. Thread(NULL, 0, Process. Client, (LPVOID)client_sock, 0, &Thread. Id); }. . . } - 23 -
q Multithread TCP Server (3/3) IT COOKBOOK • Getting socket-related address information int getpeername ( SOCKET s, struct sockaddr* name, int* namelen ); success: 0, fail: SOCKET_ERROR int getsockname ( SOCKET s, struct sockaddr* name, int* namelen ); success: 0, fail: SOCKET_ERROR • TCPServer 2. cpp - 24 -
q thread synchronization (1/4) IT COOKBOOK • Why does thread synchronization need? – When two or more threads access the shared data in multithread environment Shard variable int money = 1000 thread 1 thread 2 . . . ① read money into ECX ② ECX = ECX + 2000 ② ECX = ECX + 4000 ③ write ECX into money . . . - 25 -
q thread synchronization (2/4) IT COOKBOOK • Various thread synchronization mechanism technique description critical section The critical section is a thread synchronization object (the critical section allows synchronization within the same process. ) synchronization object used to synchronize threads with mutex more than one process. Event is a thread synchronization object used to set the event semaphore signaled or non-signaled state thread synchronization object that allows accessing the resource for a count between zero and maximum number of threads - 26 -
q critical section (1/3) IT COOKBOOK • critical section – Critical section allows accessing only one thread at a time • features – Thread synchronization within the process – faster compared to other synchronization objects - 27 -
q critical section (2/3) IT COOKBOOK • Critical section example #include <windows. h> CRITICAL_SECTION cs; // ① // thread 1 DWORD WINAPI Thread 1(LPVOID arg) {. . . Enter. Critical. Section(&cs); // ③ // access shared resource Leave. Critical. Section(&cs); // ④. . . } - 28 -
q critical section (3/3) IT COOKBOOK • Critical section example (cont’d) // thread 2 DWORD WINAPI Thread 2(LPVOID arg) {. . . Enter. Critical. Section(&cs); // ③ // access shared resource Leave. Critical. Section(&cs); // ④. . . } int main() {. . . Initialize. Critical. Section(&cs); // ② // thread creation and exit Delete. Critical. Section(&cs); // ⑤. . . } • Ex. Critical. Section. cpp - 29 -
q Event object (1/3) IT COOKBOOK • event object – Used to notify a specific event to other thread • Event synchronization example ① event object creation to non-signaled state ② a thread is working, remaining threads are waiting for event to be signaled state ③ when a thread finish the job, set the event to signal state ④ waiting threads are doing their jobs - 30 -
q Event object (2/3) IT COOKBOOK • Event object state setting BOOL Set. Event (HANDLE h. Event) ; // non-signaled state BOOL Reset. Event (HANDLE h. Event) ; // signaled state non-signaled state • Event types – auto-reset event – manual-reset event - 31 -
q Event object (3/3) IT COOKBOOK • Event object creation HANDLE Create. Event ( LPSECURITY_ATTRIBUTES lp. Event. Attributes, BOOL b. Manual. Reset, BOOL b. Initial. State, LPCTSTR lp. Name ); success: event handle, fail: NULL • Ex. Event. cpp - 32 -
- Slides: 33