




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、Thread Benefits of thread Simplify handle event Share memory and file descriptors Throughput can be improved Improved response time Process items - Address space- Global variables- Open files,- Current working directory- Timers- Signals- Semaphores- Accounting information- User and group IdsThread i
2、tems - Thread ID- Program counter - Stack (for local variables and return addresses)- State- Register set- Priority- ErrnoThread Identification A thread ID is represented by the pthread_t data type - Linux 2.4.22 : unsigned long integer - Solaris 9 : unsigned integer. - FreeBSD 5.2.1 and Mac OS X 10
3、.3 : pointer to the pthread structure for the pthread_t data type. int pthread_equal(pthread_t tid1, pthread_t tid2) pthread_t pthread_self(void)Thread CreationAdditional threads created by pthread_create function:#include int pthread_create ( pthread_t *tid, const pthread_attr_t *attr, void * (*fun
4、c) (void *), void *arg);- tid is the thread ID (returned by the call)- attr attributes: initial stack size, priority, should be a daemon thread or notspecify these attributes by initializing a pthread_attr_t variable.default:NULL - func:address of thread start function. - arg points to a set of para
5、meters to be passed to the function when it is called. return value from pthread functions is either 0: OK, positive number (Exxx):Example of threadpthread_t ntid; void printids(const char *s) pid_t pid; pthread_t tid; pid = getpid(); tid = pthread_self(); printf(%s pid %u tid %u (0 x%x)n, s, (unsig
6、ned int)pid, (unsigned int)tid, (unsigned int)tid); void * thr_fn(void *arg) printids(new thread: ); return(void *)0); Example of threadint main(void) int err; err = pthread_create(&ntid, NULL, thr_fn, NULL); if (err != 0) err_quit(cant create thread: %sn, strerror(err); printids(main thread:);
7、sleep(1); exit(0); Result:./a.out new thread: pid 6628 tid 1026 (0 x402) main thread: pid 6626 tid 1024 (0 x400) Thread Termination Any thread within a process calls exit, _Exit, or _exit, = the entire process terminates. Defaultly, a signal sent to a thread will terminate the entire process Thread
8、TerminationSimply return from the start routine. The return value is the threads exit code.Canceled by another thread in the same process.Call pthread_exit. void pthread_exit(void *rval_ptr); rval_ptr : typeless pointer, available to other threads in the process by calling the pthread_join function.
9、Waiting for a thread One thread can wait for another thread to terminate by calling the pthread_join function: (similar to waitpid() for process) #include int pthread_join (pthread_t tid, void *status); - tid is thread id of the process we want to wait - *status, if not null, takes the return value
10、from the thread as a pointer to some object Incorrect use of pthread_exit argumentstruct foo int a, b, c, d; ; void printfoo(const char *s, const struct foo *fp) printf(s); printf( structure at 0 x%xn, (unsigned)fp); printf( foo.a = %dn, fp-a); printf( foo.b = %dn, fp-b); printf( foo.c = %dn, fp-c);
11、 printf( foo.d = %dn, fp-d); Incorrect use of pthread_exit argumentvoid * thr_fn1(void *arg) struct foo foo = 1, 2, 3, 4; printfoo(thread 1:n, &foo); pthread_exit(void *)&foo); void * thr_fn2(void *arg) printf(thread 2: ID is %dn, pthread_self(); pthread_exit(void *)0); Incorrect use of pthr
12、ead_exit argumentint main(void) int err; pthread_t tid1, tid2; struct foo *fp; err = pthread_create(&tid1, NULL, thr_fn1, NULL); if (err != 0) err_quit(cant create thread 1: %sn, strerror(err); err = pthread_join(tid1, (void *)&fp); if (err != 0) err_quit(cant join with thread 1: %sn, strerr
13、or(err); sleep(1); printf(parent starting second threadn); err = pthread_create(&tid2, NULL, thr_fn2, NULL); if (err != 0) err_quit(cant create thread 2: %sn, strerror(err); sleep(1); printfoo(parent:n, fp); exit(0); Incorrect use of pthread_exit argumentResult:$ ./a.out $ ./a.out thread 1: thre
14、ad 1: structure at 0 x409a2abc structure at 0 x409a2abc foo.a = 1 foo.a = 1 foo.b = 2 foo.b = 2 foo.c = 3 foo.d = 4 foo.c = 3 foo.d = 4 parent starting second thread parent starting second thread thread 2: thread 2: ID is 32770 ID is 32770 parent: parent: structure at 0 x409a2abc structure at 0 x409
15、a2abc foo.a = 0 foo.a = 0 foo.b = 32770 foo.b = 32770 foo.c = 1075430560 foo.c = 1075430560 foo.d = 1073937284 foo.d = 1073937284 Detach The term detaching means cleaning up after a thread and reclaiming its storage space. Two ways to achieve this: - calling the pthread_join function and waiting for
16、 it to terminate- setting the detach attribute of the thread (either at creation time or dynamically by calling the pthread_detach function: (a thread is either joinable or detached)Exit functionsvoid pthread_cleanup_push(void (*rtn)(void *), void *arg); void pthread_cleanup_pop(int execute); Implem
17、ented as macros Similar to atexit function, schedules the cleanup function, rtn, called with the single argument, arg, when the thread performs one of the following actions: - Makes a call to pthread_exit - Responds to a cancellation request - Makes a call to pthread_cleanup_pop with a nonzero If th
18、e execute argument is zero, the cleanup function is not called. In either case, pthread_cleanup_pop removes the cleanup handler established by the last call to pthread_cleanup_push.Comparison of process and thread primitivesMutexes: Locking and Unlocking Mutexes are used to provide mutually exclusiv
19、e access to critical sections. Posix mutexs are variables declared to be of type pthread_mutex_t Statically allocated mutexes can be initialized to the constant PTHREAD_MUTEX_INITIALIZER: static pthread_mutex_t mtxlock = PTHREAD_MUTEX_INITIALIZER;( mutex status is locked or unlocked)Mutexes Dynamica
20、lly allocated mutexes can be initialized at run time by calling the pthread_mutex_init function. Lock and unlock functions: #include int pthread_mutex_lock(pthread_mutex_t *mptr); (if the mutex is locked by some other thread, then we are blocked until the mutex is unlocked) int pthread_mutex_trylock
21、 (pthread_mutex_t *mptr); int pthread_mutex_unlock (pthread_mutex_t *mptr); * trylock returns EBUSY if the mutex is already lockedMutexes The normal usage: pthread_mutex_lock (the_mutex);. Critical Section pthread_mutex_unlock (the_mutex);Mutex example Two threads that increment a global variable in
22、correctly See: example01.c Two threads that increment a global variable correctly See: threads/example02.cTo compile those programs cc progrm -lpthread example01.c(1/2)#include pthread.h #define NLOOP 5000 int counter; /* incremented by threads */ void *doit(void *); int main(int argc, char *argv) p
23、thread_t tidA, tidB; pthread_create(&tidA, NULL, &doit, NULL); pthread_create(&tidB, NULL, &doit, NULL); /* wait for both threads to terminate */ pthread_join(tidA, NULL); pthread_join(tidB, NULL); exit(0); example01.c(2/2)void * doit(void *vptr) int i, val; /*Each thread fetches, pr
24、ints, and increments the counter NLOOP times. The value of the counter should increase monotonically. */ for (i = 0; i NLOOP; i+) val = counter; printf(%d: %dn, pthread_self(), val + 1); counter = val + 1; return (NULL);example02.c(1/2)#include pthread.h #define NLOOP 5000 int counter; /* incremente
25、d by threads */ pthread_mutex_t counter_mutex =PTHREAD_MUTEX_INITIALIZER; void *doit(void *); int main(int argc, char *argv) pthread_t tidA, tidB; thread_create(&tidA, NULL, &doit, NULL); thread_create(&tidB, NULL, &doit, NULL); /* wait for both threads to terminate */ thread_join(ti
26、dA, NULL); thread_join(tidB, NULL); exit(0); example02.c(2/2)void * (void *vptr) int i, val; /* Each thread fetches, prints, and increments the counter NLOOP times. The value of the counter should increase monotonically. */ for (i = 0; i NLOOP; i+) pthread_mutex_lock(&counter_mutex); val = count
27、er; printf(%d: %dn, pthread_self(), val + 1); counter = val + 1; pthread_mutex_unlock(&counter_mutex); return (NULL); Reader-Write lock locked in read mode locked in write mode Unlocked Apis:int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock); int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
28、 int pthread_rwlock_unlock(pthread_rwlock_t *rwlock); Condition Variables: Waiting and Signaling A mutex is for locking and a condition variable is for waiting. A condition variable is a variable of type: pthread_cond_t The associated functions are:#include int pthread_cond_wait(pthread_cond_t *cptr
29、, pthread_mutex_t *mptr); int pthread_cond_signal( pthread_cond_t *cptr);(both return zero on success, nonzero on error)Condition Variables A condition variable is always associated with a mutex.Condition variable is a signaling mechanism associated with a mutex. When a thread waits on a condition v
30、ariable, its lock on the associated mutex is released. When the thread successfully returns from the wait, it again holds the lock.General structure of the code that waits on a condition variable:struct pthread_mutex_tmutex;pthread_cond_tcond;/* variables for maintaining the condition */ varx = PTHR
31、EAD_MUTEX_INITIALIZER, initialize mutexPTHREAD_COND_INITIALIZER, initialize condition var ; pthread_mutex_lock(&var.mutex);while (condition is false)pthread_cond_wait(&var.cond, &var.mutex); modify condition.pthread_mutex_unlock(&var.mutex);General structure of the code that signals a condition variabl
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 在教師節(jié)表彰大會(huì)上發(fā)言稿(16篇)
- 供電指揮練習(xí)試題
- 描述表達(dá)小王子的讀書心得(15篇)
- 網(wǎng)絡(luò)組件與工作原理試題及答案
- 廚房調(diào)味品大全明細(xì)表
- 高效復(fù)習(xí)計(jì)算機(jī)三級(jí)數(shù)據(jù)庫(kù)考試試題及答案
- 市場(chǎng)租賃運(yùn)營(yíng)管理合同書
- 農(nóng)業(yè)生物技術(shù)實(shí)踐技能測(cè)試題
- 網(wǎng)絡(luò)存儲(chǔ)技術(shù)應(yīng)用試題及答案
- 游戲電競(jìng)行業(yè)直播平臺(tái)搭建技術(shù)方案
- php設(shè)備管理系統(tǒng)論文
- 2019年壓力性損傷預(yù)防治療臨床實(shí)踐指南
- 2024年01月東莞濱海灣新區(qū)管理委員會(huì)下屬事業(yè)單位2024年公開選聘1名人員筆試歷年典型考題及考點(diǎn)研判與答案解析
- (高清版)JTGT 3360-01-2018 公路橋梁抗風(fēng)設(shè)計(jì)規(guī)范
- 異丙醇體檢方案
- 2024國(guó)家能源集團(tuán)寧夏煤業(yè)有限責(zé)任公司校園招聘筆試參考題庫(kù)含答案解析
- 山東省煙草專賣局(公司)筆試試題2023
- 醫(yī)院保潔服務(wù)投標(biāo)方案(技術(shù)方案)
- 【美的集團(tuán)企業(yè)應(yīng)收賬款現(xiàn)狀、問(wèn)題及對(duì)策(論文6200字)】
- 老年護(hù)理職業(yè)前景課件
- 頭孢他啶在血液腦屏障中的分布及代謝
評(píng)論
0/150
提交評(píng)論