版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
1、Chapter 5 Linux Multi-thread Programming李素科北京大學軟件與微電子學院2007,2,What is a thread?,A thread is an independent sequence of execution of program code inside a UNIX process A thread is often called a lightweight process but it is NOT a process (something smaller than a process),process space,thread,3,Why
2、Threads?,Do concurrent control more efficiently Use fork() to create a process: is expensive, usually the child process need copy the whole context from the parent process. Inter-process communication is expensive and difficult. OS does more effort to switch process contexts. Creating a thread Threa
3、ds use and exist within the process resources, so creating a thread is faster than creating a process. Inter-thread communication is easy, usually we can use global variable or struct to share data between threads. OS switches thread contexts easier than process contexts.,4,Shared or Not Shared betw
4、een thread and process,Shared process instruction most data(A thread can have its own private data) open files signal handlers and signal dispositions current working directory user and group ID Not shared thread ID set of registers (including pc and sp) stack signal mask priority,5,What are Pthread
5、s?,IEEE POSIX standard p1003.1c (Pthreads) specifies the APIs and the way other POSIX interfaces deal with threads Pthreads are defined as a set of C language programming types and procedure calls i.e. Create a new thread: #include int pthread_create(pthread_t * thread, pthread_attr_t * attr, void *
6、 (*start_routine)(void *), void * arg); We want to link a pthread application in Linux , we need libpthread library. so, you can compile file with -lpthread flag # gcc xxxx.c -o xxxx -lpthread,6,Creating Threads,#include int pthread_create(pthread_t * thread, pthread_attr_t * attr, void *(*start_rou
7、tine)(void *), void * arg);,thread identifier,thread attribute pthread_attr_init() sets the attribute of a thread,point to function, What does the thread do?,Sometime, you need pass some arguments to the thread function,Return value: On success, the identifier of the newly created thread is stored i
8、n the location pointed by the thread argument, and a 0 is returned. On error, a non-zero error code is returned.,7,Waiting For the Termination of Threads,#include int pthread_join(pthread_t th, void *thread_return); pthread_join suspends the execution of the calling thread until the thread identifie
9、d by th terminates If thread_return is not NULL, the return value of th is stored in the location pointed to by thread_return The joined thread th must be in the joinable state: it must not have been detached using pthread_detach or the PTHREAD_CREATE_DETACHED attribute to pthread_create pthread_joi
10、n must be called once for each joinable thread created to avoid memory leaks,because memory resources (thread descriptor and stack) of joinable threads are not deallocated if the caller do not call pthread_join.,Waiting for th to terminate,8,Destroying Threads,#include void pthread_exit(void *retval
11、); Ways for threads to terminate: The thread returns from its starting routine; The thread calls pthread_exit (); The thread is canceled by another thread via pthread_cancel(); The thread receives a signal that terminates it; The entire process is terminated.,return value of the thread,can not point
12、 to local thread object,9,pthread_detach,#include int pthread_detach(pthread_t th); This guarantees that the memory resources consumed by th will be freed immediately when th terminates. But this prevents other threads from synchronizing on the termination of th using pthread_join. A thread can be c
13、reated initially in the detached state, using the detachstate attribute to pthread_create. After pthread_detach completes, subsequent attempts to perform pthread_join on th will fail. If another thread is already joining the thread th at the time pthread_detach is called, pthread_detach does nothing
14、 and leaves th in the joinable state. On success, 0 is returned. On error, a non-zero error code is returned.,10,pthread_self,#include pthread_t pthread_self(void); return identifier of current thread,11,Mutex-protecting your critical sections, pthread_mutex_t mylock; mylock = PTHREAD_MUTEX_INITIALI
15、ZER; pthread_mutex_lock( ,A mutex will be owned by only one thread at one time If another thread call pthread_mutex_lock() on a unlocked mutex, another thread which calls pthread_mutex_lock too is suspended and waits for the owner of locked mutex thread to unlock the mutex first.,12,Avoiding Deadloc
16、ks,/* Thread A */ pthread_mutex_lock(,/* Thread B */ pthread_mutex_lock(,time,13,Avoiding Deadlocks Cont.,pthread_mutex_lock(,time,pthread_mutex_lock(,14,Operations on Mutexes,#include pthread_mutex_t fastmutex = PTHREAD_MUTEX_INITIALIZER; int pthread_mutex_init(pthread_mutex_t *mutex, const pthread
17、_mutex- attr_t *mutexattr); int pthread_mutex_lock(pthread_mutex_t *mutex); int pthread_mutex_trylock(pthread_mutex_t *mutex); int pthread_mutex_unlock(pthread_mutex_t *mutex); int pthread_mutex_destroy(pthread_mutex_t *mutex); In the LinuxThreads implementation, no resources are associated with mut
18、ex objects, thus pthread_mutex_destroy actually does nothing except checking that the mutex is unlocked.,15,It is time to write a simple program,#include #include #include #include #define THREAD_NUMBER 10 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int sum =0; void* inc(void *arg) int
19、 i =(*(int *)arg); pthread_mutex_lock( ,16,Cont,int main(int argc, char *argv) pthread_t ptTHREAD_NUMBER; int i; int argTHREAD_NUMBER; for(i=0; iTHREAD_NUMBER; i+) argi=i; if(pthread_create( ,Compile: #gcc counter.c o counter -lpthread Run it:# ./counter sum is 45,17,Multi-thread Web Client,This exa
20、mple is modified from the book UNIX Network Programming, Volume 1, by Richard Stevens #include #include #include #include #include #include #include #include #include #include #include #define MAXLINE 1024 #define MAXFILES20 #define SERV80 /* port number or service name */,18,Cont,struct file char *
21、f_name; /* filename */ char *f_host; /* hostname or IP address */ int f_fd; /* descriptor */ int f_flags; /* F_xxx below */ unsigned long int f_tid; /* thread ID */ fileMAXFILES; #define F_CONNECTING 1 /* connect() in progress */ #define F_READING 2 /* connect() complete; now reading */ #define F_DO
22、NE 4 /* all done */ #define F_JOINED 8 /* main has pthread_joined */ #define GET_CMD GET %s HTTP/1.0rnrn int nconn, nfiles, nlefttoconn, nlefttoread; int ndone; /* number of terminated threads*/ pthread_mutex_t ndone_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t ndone_cond = PTHREAD_COND_INITIAL
23、IZER;,19,Cont,main(int argc, char *argv) inti, maxnconn; pthread_t tid; struct file *fptr; if (argc file1 .n); exit(0); maxnconn = atoi(argv1); if(argc-4) MAXFILES) nfiles = MAXFILES; else nfiles = argc -4; for (i = 0; i nfiles; i+) filei.f_name = argvi + 4; filei.f_host = argv2; filei.f_flags = 0;
24、,20,Cont,printf(nfiles = %dn, nfiles); home_page(argv2, argv3); nlefttoread = nlefttoconn = nfiles; nconn = 0; while (nlefttoread 0) while (nconn 0) /* 4find a file to read */ for (i = 0 ; i nfiles; i+) if (filei.f_flags = 0) break; if (i = nfiles) printf(nlefttoconn = %d but nothing found, nlefttoc
25、onn); exit(1); pthread_create( ,21,Cont,pthread_mutex_lock( ,思考,如果不用這個API, 該如何改這個程序?,22,Cont- do_get_read,void *do_get_read(void *vptr) intfd, n; charlineMAXLINE; struct file*fptr; fptr = (struct file *) vptr; fd = tcp_connect(fptr-f_host, SERV); fptr-f_fd = fd; printf(do_get_read for %s, fd %d, thr
26、ead %dn, fptr-f_name, fd, fptr-f_tid); write_get_cmd(fptr); /* write() the GET command */ /* 4Read servers reply */ for ( ; ; ) if ( (n = read(fd, line, MAXLINE) = 0) break;/* server closed connection */,23,Cont- do_get_read,printf(read %d bytes from %sn, n, fptr-f_name); printf(end-of-file on %sn,
27、fptr-f_name); close(fd); fptr-f_flags = F_DONE; /* clears F_READING */ pthread_mutex_lock( /* terminate thread */ ,24,Result,rootlocalhost multithreadwebclient# g+ multith_web.c -o multith_web -lpthread rootlocalhost multithreadwebclient# ./multith_web 3 / /templates/sspku_gate_index/images/index_04
28、.gif /images/banners/logo_xiaoli.png /images/banners/logo_COS2.jpg nfiles = 3 read 1024 bytes of home page . end-of-file on home page do_get_read for /templates/sspku_gate_index/images/index_04.gif, fd 3, thread 3086826400 wrote 64 bytes for /templates/sspku_gate_index/images/index_04.gif do_get_rea
29、d for /images/banners/logo_COS2.jpg, fd 6, thread 3065846688 wrote 46 bytes for /images/banners/logo_COS2.jpg do_get_read for /images/banners/logo_xiaoli.png, fd 5, thread 3076336544 wrote 48 bytes for /images/banners/logo_xiaoli.png .,25,Pthread-operations on conditions,#include pthread_cond_t cond
30、 = PTHREAD_COND_INITIALIZER; int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr); int pthread_cond_signal(pthread_cond_t *cond); int pthread_cond_broadcast(pthread_cond_t *cond); int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex); int pthread_cond_timedwait(pt
31、hread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime); int pthread_cond_destroy(pthread_cond_t *cond);,26,pthread_cond_t,A condition is a synchronization device that allows threads to suspend execution and relinquish the processors until some predicate on shared data is satisfi
32、ed. The basic operations on conditions are: signal the condition (when the predicate becomes true), and wait for the condition, suspending the thread execution until another thread signals the condition.,27,pthread_cond_t,A condition variable must always be associated with a mutex, to avoid the race
33、 condition where a thread prepares to wait on a condition variable and another thread signals the condition just before the first thread actually waits on it.,28,pthread_cond_init,#include int pthread_cond_init (pthread_cond_t *cond, pthread_condattr_t*cond_attr); pthread_cond_init initializes the c
34、ondition variable cond, using the condition attributes specified in cond_attr, or default attributes cond_attr is NULL. The LinuxThreads implementation supports no attributes for conditions, hence the cond_attr parameter is actually ignored. Variables of type pthread_cond_t can also be initialized s
35、tatically, using the constant PTHREAD_COND_INITIALIZER. return 0 on success and a non-zeroerror code on error; not return error code.,29,Example,pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; Or : / initialize the condition variable if(pthread_cond_i
36、nit ( pthread_cond_signal restarts one of the threads that are waiting on the condition variable cond. If no threads are waiting on cond, nothing happens. If several threads are waiting on cond, exactly one is restarted, but it is not specified which. return 0 on success and a non-zeroerror code on
37、error; not return error code.,31,Example,pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; Or : / initialize the condition variable if(pthread_cond_init ( ,32,pthread_cond_broadcast,#include int pthread_cond_broadcast(pthread_cond_t *cond); pthread_cond
38、_broadcast restarts all the threads that are waiting on the condition variable cond. Nothing happens if no threads are waiting on cond. return 0 on success and a non-zeroerror code on error; not return error code.,33,Example,pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHR
39、EAD_COND_INITIALIZER; Or : / initialize the condition variable if(pthread_cond_init ( ,34,pthread_cond_wait,#include int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex); pthread_cond_wait atomically unlocks the mutex (as per pthread_unlock_mutex) and waits for the condition variable
40、cond to be signaled. The thread execution is suspended and does not consume any CPU time until the condition variable is signaled.,35,Cont,The mutex must be locked by the calling thread on entrance to pthread_cond_wait. Before returning to the calling thread, pthread_cond_wait re-acquires mutex (as
41、per pthread_lock_mutex). For example while (ndone = 0) pthread_cond_wait( not return error code.,37,Example,pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; Or : / initialize the condition variable if(pthread_cond_init ( ,38,pthread_cond_timedwait,#inc
42、lude int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime); pthread_cond_timedwait atomically unlocks mutex and waits on cond, as pthread_cond_wait does, but it also bounds the duration of the wait.,39,Cont,If cond has not been signaled within the a
43、mount of time specified by abstime, the mutex is reacquired and pthread_cond_timedwait returns the error ETIMEDOUT. The abstime parameter specifies an absolute time, with the same origin as time(2) and gettimeofday(2): from 00:00:00 GMT, January 1, 1970.,40,pthread_cond_destroy,#include int pthread_
44、cond_destroy(pthread_cond_t *cond); pthread_cond_destroy destroys a condition variable, freeing the resources it might hold. No threads must be waiting on the condition variable on entrance to pthread_cond_destroy. In the LinuxThreads implementation, no resources are associated with condition variab
45、les, thus pthread_cond_destroy actually does nothing except checking that the condition has no waiting threads.,41,An Example from Linux Manual,pthread_mutex_lock(,pthread_mutex_lock(,int x,y; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER;,Thread A,Thread B,42,Another Example from Linux Manual,struct timeval now; struct timespec timeout; int retcode; pthread_mutex_lock(,43,Workshop,Modify the program counter.c then le
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2026年建筑師考試建筑構造與材料試題集
- 2026年貴陽康養(yǎng)職業(yè)大學單招綜合素質筆試模擬試題含詳細答案解析
- 2026年鄭州電力職業(yè)技術學院單招綜合素質筆試模擬試題含詳細答案解析
- 2026年云南工貿職業(yè)技術學院單招職業(yè)技能考試參考題庫含詳細答案解析
- 2026年保定電力職業(yè)技術學院單招綜合素質考試備考試題含詳細答案解析
- 2026年山西管理職業(yè)學院單招綜合素質考試參考題庫含詳細答案解析
- 2026中國科學院云南天文臺撫仙湖太陽觀測和研究基地望遠鏡工程師招聘1人考試重點試題及答案解析
- 2026年青島電影學院高職單招職業(yè)適應性測試備考題庫及答案詳細解析
- 2026年云南體育運動職業(yè)技術學院高職單招職業(yè)適應性測試備考題庫及答案詳細解析
- 2026年長沙民政職業(yè)技術學院單招綜合素質筆試參考題庫含詳細答案解析
- 2025-2026學年北京市朝陽區(qū)高一(上期)期末考試英語試卷(含答案)
- 2026湖南衡陽耒陽市公安局招聘75名警務輔助人員考試參考題庫及答案解析
- 電力工程施工方案及規(guī)范
- 2026年1月浙江省高考(首考)英語試題(含答案詳解)+聽力音頻+聽力材料
- 2026年時事政治測試題庫附完整答案(網(wǎng)校專用)
- 智慧物流背景下多式聯(lián)運的協(xié)同發(fā)展與運輸效能提升研究畢業(yè)論文答辯匯報
- 替人背債合同范本
- 山西省運城市小學一年級上學期數(shù)學期末考試試題
- 藥師處方審核管理制度
- T-HHPA 001-2025 老年人跌倒風險評估及干預措施
- 2025年廣西高考地理真題(解析版)
評論
0/150
提交評論