国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

淺析C++編程當(dāng)中的線程

2020-05-23 14:17:14
字體:
供稿:網(wǎng)友

這篇文章主要介紹了淺析C++編程當(dāng)中的線程,線程在每一種編程語言中都是重中之重,需要的朋友可以參考下

線程的概念

C++中的線程的Text Segment和Data Segment都是共享的,如果定義一個(gè)函數(shù),在各線程中都可以調(diào)用,如果定義一個(gè)全局變量,在各線程中都可以訪問到。除此之外,各線程還共享以下進(jìn)程資源和環(huán)境:

文件描述符

每種信號的處理方式

當(dāng)前工作目錄

用戶id和組id

但是,有些資源是每個(gè)線程各有一份的:

線程id

上下文,包括各種寄存器的值、程序計(jì)數(shù)器和棧指針

棧空間

errno變量

信號屏蔽字

調(diào)度優(yōu)先級

我們將要學(xué)習(xí)的線程庫函數(shù)是由POSIX標(biāo)準(zhǔn)定義的,稱為POSIX thread或pthread。

線程控制 創(chuàng)建線程

創(chuàng)建線程的函數(shù)原型如下:

 

 
  1. #include <pthread.h> 
  2. int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg); 

返回值:成功返回0,失敗返回錯(cuò)誤號。

在一個(gè)線程中調(diào)用pthread_create()創(chuàng)建新的線程后,當(dāng)前線程從pthread_create()返回繼續(xù)往下執(zhí)行,而新的線程所執(zhí)行的代碼由我們傳給pthread_create的函數(shù)指針start_routine決定。start_routine函數(shù)接收一個(gè)參數(shù),是通過pthread_create的arg參數(shù)傳遞給它的,該參數(shù)類型為void*,這個(gè)指針按什么類型解釋由調(diào)用者自己定義。start_routine的返回值類型也是void *,這個(gè)指針的含義同樣由調(diào)用者自己定義。start_routine返回時(shí),這個(gè)線程就退出了,其它線程可以調(diào)用pthread_join得到start_routine的返回值。

pthread_create成功返回后,新創(chuàng)建的線程的id被填寫到thread參數(shù)所指向的內(nèi)存單元。我們知道進(jìn)程id的類型是pid_t,每個(gè)進(jìn)程的id在整個(gè)系統(tǒng)中是唯一的,調(diào)用getpid可以得到當(dāng)前進(jìn)程的id,是一個(gè)正整數(shù)值。線程id的類型是thread_t,它只在當(dāng)前進(jìn)程中保證是唯一的,在不同的系統(tǒng)中thread_t這個(gè)類型有不同的實(shí)現(xiàn),它可能是一個(gè)整數(shù)值,也可能是一個(gè)結(jié)構(gòu)體,也可能是一個(gè)地址,所以不能簡單的當(dāng)成整數(shù)用printf打印,調(diào)用pthread_self可以獲取當(dāng)前線程的id。

我們先來寫一個(gè)簡單的例子:

 

 
  1. #include <stdio.h> 
  2. #include <string.h> 
  3. #include <stdlib.h> 
  4. #include <pthread.h> 
  5. #include <unistd.h> 
  6.  
  7. pthread_t ntid; 
  8.  
  9. void printids(const void *t) 
  10. char *s = (char *)t; 
  11. pid_t pid; 
  12. pthread_t tid; 
  13.  
  14. pid = getpid(); 
  15. tid = pthread_self(); 
  16. printf("%s pid %u tid %u (0x%x)/n", s, (unsigned int)pid, 
  17. (unsigned int)tid, (unsigned int)tid); 
  18.  
  19. void *thr_fn(void *arg) 
  20. printids(arg); 
  21. return NULL; 
  22.  
  23. int main(void
  24. int err; 
  25.  
  26. err = pthread_create(&ntid, NULL, thr_fn, (void *)"Child Process:"); 
  27. if (err != 0) { 
  28. fprintf(stderr, "can't create thread: %s/n", strerror(err)); 
  29. exit(1); 
  30. printids("main thread:"); 
  31. sleep(1); 
  32.  
  33. return 0; 

編譯執(zhí)行結(jié)果如下:

 

 
  1. g++ thread.cpp -o thread -lpthread 
  2. ./thread 
  3. main thread: pid 21046 tid 3612727104 (0xd755d740) 
  4. Child Process: pid 21046 tid 3604444928 (0xd6d77700) 

從結(jié)果可以知道,thread_t類型是一個(gè)地址值,屬于同一進(jìn)程的多個(gè)線程調(diào)用getpid可以得到相同的進(jìn)程號,而調(diào)用pthread_self得到的線程號各不相同。

如果任意一個(gè)線程調(diào)用了exit或_exit,則整個(gè)進(jìn)程的所有線程都終止,由于從main函數(shù)return也相當(dāng)于調(diào)用exit,為了防止新創(chuàng)建的線程還沒有得到執(zhí)行就終止,我們在main函數(shù)return之前延時(shí)1秒,這只是一種權(quán)宜之計(jì),即使主線程等待1秒,內(nèi)核也不一定會調(diào)度新創(chuàng)建的線程執(zhí)行,接下來,我們學(xué)習(xí)一下比較好的解決方法。

終止線程

如果需要只終止某個(gè)線程而不是終止整個(gè)進(jìn)程,可以有三種方法:

從線程函數(shù)return。這種方法對主線程不適應(yīng),從main函數(shù)return相當(dāng)于調(diào)用exit。

一個(gè)線程可以調(diào)用pthread_cancel終止同一個(gè)進(jìn)程中的另一個(gè)線程。

線程可以調(diào)用pthread_exit終止自己。

這里主要介紹pthread_exit和pthread_join的用法。

 

 
  1. #include <pthread.h> 
  2.  
  3. void pthread_exit(void *value_ptr); 

value_ptr是void*類型,和線程函數(shù)返回值的用法一樣,其它線程可以調(diào)用pthread_join獲取這個(gè)指針。

需要注意,pthread_exit或者return返回的指針?biāo)赶虻膬?nèi)存單元必須是全局的或者是用malloc分配的,不能在線程函數(shù)的棧上分配,因?yàn)楫?dāng)其它線程得到這個(gè)返回指針時(shí)線程函數(shù)已經(jīng)退出了。

 

 
  1. #include <pthread.h> 
  2.  
  3. int pthread_join(pthread_t thread, void **value_ptr); 

返回值:成功返回0,失敗返回錯(cuò)誤號。

調(diào)用該函數(shù)的線程將掛起等待,直到id為thread的線程終止。thread線程以不同的方法終止,通過pthread_join得到的終止?fàn)顟B(tài)是不同的,總結(jié)如下:

如果thread線程通過return返回,value_ptr所指向的單元里存放的是thread線程函數(shù)的返回值。

如果thread線程被別的線程調(diào)用pthread_cancel異常終止掉,value_ptr所指向的單元存放的是常數(shù)PTHREAD_CANCELED。

如果thread線程是自己調(diào)用pthread_exit終止的,value_ptr所指向的單元存放的是傳給pthread_exit的參數(shù)。

如果對thread線程的終止?fàn)顟B(tài)不感興趣,可以傳NULL給value_ptr參數(shù)。參考代碼如下:

 

 
  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. #include <pthread.h> 
  4. #include <unistd.h> 
  5.  
  6. void* thread_function_1(void *arg) 
  7. printf("thread 1 running/n"); 
  8. return (void *)1; 
  9.  
  10. void* thread_function_2(void *arg) 
  11. printf("thread 2 exiting/n"); 
  12. pthread_exit((void *) 2); 
  13.  
  14. void* thread_function_3(void* arg) 
  15. while (1) { 
  16. printf("thread 3 writeing/n"); 
  17. sleep(1); 
  18.  
  19.  
  20. int main(void
  21. pthread_t tid; 
  22. void *tret; 
  23.  
  24. pthread_create(&tid, NULL, thread_function_1, NULL); 
  25. pthread_join(tid, &tret); 
  26. printf("thread 1 exit code %d/n", *((int*) (&tret))); 
  27.  
  28. pthread_create(&tid, NULL, thread_function_2, NULL); 
  29. pthread_join(tid, &tret); 
  30. printf("thread 2 exit code %d/n", *((int*) (&tret))); 
  31.  
  32. pthread_create(&tid, NULL, thread_function_3, NULL); 
  33. sleep(3); 
  34. pthread_cancel(tid); 
  35. pthread_join(tid, &tret); 
  36. printf("thread 3 exit code %d/n", *((int*) (&tret))); 
  37.  
  38. return 0; 

運(yùn)行結(jié)果是:

 

 
  1. thread 1 running 
  2. thread 1 exit code 1 
  3. thread 2 exiting 
  4. thread 2 exit code 2 
  5. thread 3 writeing 
  6. thread 3 writeing 
  7. thread 3 writeing 
  8. thread 3 exit code -1 

可見,Linux的pthread庫中常數(shù)PTHREAD_CANCELED的值是-1.可以在頭文件pthread.h中找到它的定義:

 

  
  1. #define PTHREAD_CANCELED ((void *) -1) 

線程間同步

多個(gè)線程同時(shí)訪問共享數(shù)據(jù)時(shí)可能會沖突,例如兩個(gè)線程都要把某個(gè)全局變量增加1,這個(gè)操作在某平臺上需要三條指令才能完成:

從內(nèi)存讀變量值到寄存器。

寄存器值加1.

將寄存器的值寫回到內(nèi)存。

這個(gè)時(shí)候很容易出現(xiàn)兩個(gè)進(jìn)程同時(shí)操作寄存器變量值的情況,導(dǎo)致最終結(jié)果不正確。

解決的辦法是引入互斥鎖(Mutex, Mutual Exclusive Lock),獲得鎖的線程可以完成“讀-修改-寫”的操作,然后釋放鎖給其它線程,沒有獲得鎖的線程只能等待而不能訪問共享數(shù)據(jù),這樣,“讀-修改-寫”的三步操作組成一個(gè)原子操作,要不都執(zhí)行,要不都不執(zhí)行,不會執(zhí)行到中間被打斷,也不會在其它處理器上并行做這個(gè)操作。

Mutex用pthread_mutex_t類型的變量表示,可以這樣初始化和銷毀:

 

  1. #include <pthread.h> 
  2.  
  3. int pthread_mutex_destory(pthread_mutex_t *mutex); 
  4. int pthread_mutex_int(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr); 
  5. pthread_mutex_t mutex = PTHEAD_MUTEX_INITIALIZER; 

返回值:成功返回0,失敗返回錯(cuò)誤號。

用pthread_mutex_init函數(shù)初始化的Mutex可以用pthread_mutex_destroy銷毀。如果Mutex變量是靜態(tài)分配的(全局變量或static變量),也可以用宏定義PTHREAD_MUTEX_INITIALIZER來初始化,相當(dāng)于用pthread_mutex_init初始化并且attr參數(shù)為NULL。Mutex的加鎖和解鎖操作可以用下列函數(shù):

 

 
  1. #include <pthread.h> 
  2.  
  3. int pthread_mutex_lock(pthread_mutex_t *mutex); 
  4. int pthread_mutex_trylock(pthread_mutex_t *mutex); 
  5. int pthread_mutex_unlock(pthread_mutex_t *mutex); 

返回值:成功返回0,失敗返回錯(cuò)誤號。

一個(gè)線程可以調(diào)用pthread_mutex_lock獲得Mutex,如果這時(shí)另一個(gè)線程已經(jīng)調(diào)用pthread_mutex_lock獲得了該Mutex,則當(dāng)前線程需要掛起等待,直到另一個(gè)線程調(diào)用pthread_mutex_unlock釋放Mutex,當(dāng)前線程被喚醒,才能獲得該Mutex并繼續(xù)執(zhí)行。

我們用Mutex解決上面說的兩個(gè)線程同時(shí)對全局變量+1可能導(dǎo)致紊亂的問題:

 

 
  1. #include <pthread.h> 
  2. #include <stdio.h> 
  3. #include <stdlib.h> 
  4.  
  5. #define NLOOP 5000 
  6.  
  7. int counter; 
  8. pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER; 
  9.  
  10. void *do_add_process(void *vptr) 
  11. int i, val; 
  12.  
  13. for (i = 0; i < NLOOP; i ++) { 
  14. pthread_mutex_lock(&counter_mutex); 
  15. val = counter; 
  16. printf("%x:%d/n", (unsigned int)pthread_self(), val + 1); 
  17. counter = val + 1; 
  18. pthread_mutex_unlock(&counter_mutex); 
  19.  
  20. return NULL; 
  21.  
  22. int main() 
  23. pthread_t tida, tidb; 
  24.  
  25. pthread_create(&tida, NULL, do_add_process, NULL); 
  26. pthread_create(&tidb, NULL, do_add_process, NULL); 
  27.  
  28. pthread_join(tida, NULL); 
  29. pthread_join(tidb, NULL); 
  30.  
  31. return 0; 

這樣,每次運(yùn)行都能顯示到10000。如果去掉鎖機(jī)制,可能就會有問題。這個(gè)機(jī)制類似于Java的synchronized塊機(jī)制。

Condition Variable

線程間的同步還有這樣一種情況:線程A需要等某個(gè)條件成立才能繼續(xù)往下執(zhí)行,現(xiàn)在這個(gè)條件不成立,線程A就阻塞等待,而線程B在執(zhí)行過程中使這個(gè)條件成立了,就喚醒線程A繼續(xù)執(zhí)行。在pthread庫中通過條件變量(Conditiion Variable)來阻塞等待一個(gè)條件,或者喚醒等待這個(gè)條件的線程。Condition Variable用pthread_cond_t類型的變量表示,可以這樣初始化和銷毀:

 

 
  1. #include <pthread.h> 
  2.  
  3. int pthread_cond_destory(pthread_cond_t *cond); 
  4. int pthread_cond_init(pthead_cond_t *cond, const pthread_condattr_t *attr); 
  5. pthread_cond_t cond = PTHREAD_COND_INITIALIZER; 

返回值:成功返回0,失敗返回錯(cuò)誤號。

和Mutex的初始化和銷毀類似,pthread_cond_init函數(shù)初始化一個(gè)Condition Variable,attr參數(shù)為NULL則表示缺省屬性,pthread_cond_destroy函數(shù)銷毀一個(gè)Condition Variable。如果Condition Variable是靜態(tài)分配的,也可以用宏定義PTHEAD_COND_INITIALIZER初始化,相當(dāng)于用pthread_cond_init函數(shù)初始化并且attr參數(shù)為NULL。Condition Variable的操作可以用下列函數(shù):

 

 
  1. #include <pthread.h> 
  2.  
  3. int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime); 
  4. int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex); 
  5. int pthread_cond_broadcast(pthread_cond_t *cond); 
  6. int pthread_cond_signal(pthread_cond_t *cond); 

可見,一個(gè)Condition Variable總是和一個(gè)Mutex搭配使用的。一個(gè)線程可以調(diào)用pthread_cond_wait在一個(gè)Condition Variable上阻塞等待,這個(gè)函數(shù)做以下三步操作:

釋放Mutex。

阻塞等待。

當(dāng)被喚醒時(shí),重新獲得Mutex并返回。

pthread_cond_timedwait函數(shù)還有一個(gè)額外的參數(shù)可以設(shè)定等待超時(shí),如果到達(dá)了abstime所指定的時(shí)刻仍然沒有別的線程來喚醒當(dāng)前線程,就返回ETIMEDOUT。一個(gè)線程可以調(diào)用pthread_cond_signal喚醒在某個(gè)Condition Variable上等待的另一個(gè)線程,也可以調(diào)用pthread_cond_broadcast喚醒在這個(gè)Condition Variable上等待的所有線程。

下面的程序演示了一個(gè)生產(chǎn)者-消費(fèi)者的例子,生產(chǎn)者生產(chǎn)一個(gè)結(jié)構(gòu)體串在鏈表的表頭上,消費(fèi)者從表頭取走結(jié)構(gòu)體。

 

  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. #include <pthread.h> 
  4. #include <unistd.h> 
  5.  
  6. struct msg { 
  7. struct msg *next; 
  8. int num; 
  9. }; 
  10.  
  11. struct msg *head; 
  12. pthread_cond_t has_product = PTHREAD_COND_INITIALIZER; 
  13. pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; 
  14.  
  15. void* consumer(void *p) 
  16. struct msg *mp; 
  17.  
  18. for(;;) { 
  19. pthread_mutex_lock(&lock); 
  20. while (head == NULL) { 
  21. pthread_cond_wait(&has_product, &lock); 
  22. mp = head; 
  23. head = mp->next; 
  24. pthread_mutex_unlock(&lock); 
  25. printf("Consume %d/n", mp->num); 
  26. free(mp); 
  27. sleep(rand() % 5); 
  28.  
  29. void* producer(void *p) 
  30. struct msg *mp; 
  31.  
  32. for(;;) { 
  33. mp = (struct msg *)malloc(sizeof(*mp)); 
  34. pthread_mutex_lock(&lock); 
  35. mp->next = head; 
  36. mp->num = rand() % 1000; 
  37. head = mp; 
  38. printf("Product %d/n", mp->num); 
  39. pthread_mutex_unlock(&lock); 
  40. pthread_cond_signal(&has_product); 
  41. sleep(rand() % 5); 
  42.  
  43. int main() 
  44. pthread_t pid, cid; 
  45. srand(time(NULL)); 
  46.  
  47. pthread_create(&pid, NULL, producer, NULL); 
  48. pthread_create(&cid, NULL, consumer, NULL); 
  49.  
  50. pthread_join(pid, NULL); 
  51. pthread_join(cid, NULL); 
  52.  
  53. return 0; 
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 新民市| 大厂| 华蓥市| 郎溪县| 滦平县| 阿拉善右旗| 林周县| 德州市| 河北区| 江门市| 正蓝旗| 玉门市| 怀化市| 兴海县| 徐汇区| 谷城县| 河曲县| 无锡市| 德兴市| 东兰县| 略阳县| 白河县| 郧西县| 施甸县| 监利县| 囊谦县| 凯里市| 资源县| 北安市| 普定县| 和龙市| 禄劝| 沈丘县| 潼关县| 祁连县| 浑源县| 缙云县| 安福县| 调兵山市| 夹江县| 曲阜市|