一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - C/C++ - 淺析C++編程當中的線程

淺析C++編程當中的線程

2021-03-04 10:23低調小一 C/C++

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

線程的概念

C++中的線程的Text Segment和Data Segment都是共享的,如果定義一個函數,在各線程中都可以調用,如果定義一個全局變量,在各線程中都可以訪問到。除此之外,各線程還共享以下進程資源和環境:

  •     文件描述符
  •     每種信號的處理方式
  •     當前工作目錄
  •     用戶id和組id

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

  •     線程id
  •     上下文,包括各種寄存器的值、程序計數器和棧指針
  •     ??臻g
  •     errno變量
  •     信號屏蔽字
  •     調度優先級

我們將要學習的線程庫函數是由POSIX標準定義的,稱為POSIX thread或pthread。
線程控制
創建線程

創建線程的函數原型如下:

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

返回值:成功返回0,失敗返回錯誤號。

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

pthread_create成功返回后,新創建的線程的id被填寫到thread參數所指向的內存單元。我們知道進程id的類型是pid_t,每個進程的id在整個系統中是唯一的,調用getpid可以得到當前進程的id,是一個正整數值。線程id的類型是thread_t,它只在當前進程中保證是唯一的,在不同的系統中thread_t這個類型有不同的實現,它可能是一個整數值,也可能是一個結構體,也可能是一個地址,所以不能簡單的當成整數用printf打印,調用pthread_self可以獲取當前線程的id。

我們先來寫一個簡單的例子:

?
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
31
32
33
34
35
36
37
38
39
40
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
 
pthread_t ntid;
 
void printids(const void *t)
{
    char *s = (char *)t;
  pid_t   pid;
  pthread_t tid;
 
  pid = getpid();
  tid = pthread_self();
  printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int)pid,
      (unsigned int)tid, (unsigned int)tid);
}
 
void *thr_fn(void *arg)
{
  printids(arg);
  return NULL;
}
 
int main(void)
{
  int err;
 
  err = pthread_create(&ntid, NULL, thr_fn, (void *)"Child Process:");
  if (err != 0) {
    fprintf(stderr, "can't create thread: %s\n", strerror(err));
    exit(1);
  }
  printids("main thread:");
  sleep(1);
 
  return 0;
}


編譯執行結果如下:

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

從結果可以知道,thread_t類型是一個地址值,屬于同一進程的多個線程調用getpid可以得到相同的進程號,而調用pthread_self得到的線程號各不相同。

如果任意一個線程調用了exit或_exit,則整個進程的所有線程都終止,由于從main函數return也相當于調用exit,為了防止新創建的線程還沒有得到執行就終止,我們在main函數return之前延時1秒,這只是一種權宜之計,即使主線程等待1秒,內核也不一定會調度新創建的線程執行,接下來,我們學習一下比較好的解決方法。
終止線程

如果需要只終止某個線程而不是終止整個進程,可以有三種方法:

  1.     從線程函數return。這種方法對主線程不適應,從main函數return相當于調用exit。
  2.     一個線程可以調用pthread_cancel終止同一個進程中的另一個線程。
  3.     線程可以調用pthread_exit終止自己。

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

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

value_ptr是void*類型,和線程函數返回值的用法一樣,其它線程可以調用pthread_join獲取這個指針。
需要注意,pthread_exit或者return返回的指針所指向的內存單元必須是全局的或者是用malloc分配的,不能在線程函數的棧上分配,因為當其它線程得到這個返回指針時線程函數已經退出了。

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

返回值:成功返回0,失敗返回錯誤號。

調用該函數的線程將掛起等待,直到id為thread的線程終止。thread線程以不同的方法終止,通過pthread_join得到的終止狀態是不同的,總結如下:

  •     如果thread線程通過return返回,value_ptr所指向的單元里存放的是thread線程函數的返回值。
  •     如果thread線程被別的線程調用pthread_cancel異常終止掉,value_ptr所指向的單元存放的是常數PTHREAD_CANCELED。
  •     如果thread線程是自己調用pthread_exit終止的,value_ptr所指向的單元存放的是傳給pthread_exit的參數。

如果對thread線程的終止狀態不感興趣,可以傳NULL給value_ptr參數。參考代碼如下:

?
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
 
void* thread_function_1(void *arg)
{
  printf("thread 1 running\n");
  return (void *)1;
}
 
void* thread_function_2(void *arg)
{
  printf("thread 2 exiting\n");
  pthread_exit((void *) 2);
}
 
void* thread_function_3(void* arg)
{
  while (1) {
    printf("thread 3 writeing\n");
    sleep(1);
  }
}
 
 
int main(void)
{
  pthread_t tid;
  void *tret;
 
  pthread_create(&tid, NULL, thread_function_1, NULL);
  pthread_join(tid, &tret);
  printf("thread 1 exit code %d\n", *((int*) (&tret)));
 
  pthread_create(&tid, NULL, thread_function_2, NULL);
  pthread_join(tid, &tret);
  printf("thread 2 exit code %d\n", *((int*) (&tret)));
 
  pthread_create(&tid, NULL, thread_function_3, NULL);
  sleep(3);
  pthread_cancel(tid);
  pthread_join(tid, &tret);
  printf("thread 3 exit code %d\n", *((int*) (&tret)));
 
  return 0;
}

 

運行結果是:

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


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

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


線程間同步

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

  •     從內存讀變量值到寄存器。
  •     寄存器值加1.
  •     將寄存器的值寫回到內存。

這個時候很容易出現兩個進程同時操作寄存器變量值的情況,導致最終結果不正確。

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

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

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


返回值:成功返回0,失敗返回錯誤號。

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

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


返回值:成功返回0,失敗返回錯誤號。

一個線程可以調用pthread_mutex_lock獲得Mutex,如果這時另一個線程已經調用pthread_mutex_lock獲得了該Mutex,則當前線程需要掛起等待,直到另一個線程調用pthread_mutex_unlock釋放Mutex,當前線程被喚醒,才能獲得該Mutex并繼續執行。

我們用Mutex解決上面說的兩個線程同時對全局變量+1可能導致紊亂的問題:

?
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
31
32
33
34
35
36
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
 
#define NLOOP 5000
 
int counter;
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
 
void *do_add_process(void *vptr)
{
  int i, val;
 
  for (i = 0; i < NLOOP; i ++) {
    pthread_mutex_lock(&counter_mutex);
    val = counter;
    printf("%x:%d\n", (unsigned int)pthread_self(), val + 1);
    counter = val + 1;
    pthread_mutex_unlock(&counter_mutex);
  }
 
  return NULL;
}
 
int main()
{
  pthread_t tida, tidb;
 
  pthread_create(&tida, NULL, do_add_process, NULL);
  pthread_create(&tidb, NULL, do_add_process, NULL);
 
  pthread_join(tida, NULL);
  pthread_join(tidb, NULL);
 
  return 0;
}

這樣,每次運行都能顯示到10000。如果去掉鎖機制,可能就會有問題。這個機制類似于Java的synchronized塊機制。
Condition Variable

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

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

返回值:成功返回0,失敗返回錯誤號。

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

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


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

  1.     釋放Mutex。
  2.     阻塞等待。
  3.     當被喚醒時,重新獲得Mutex并返回。

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

下面的程序演示了一個生產者-消費者的例子,生產者生產一個結構體串在鏈表的表頭上,消費者從表頭取走結構體。

?
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
 
struct msg {
  struct msg *next;
  int num;
};
 
struct msg *head;
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
 
void* consumer(void *p)
{
  struct msg *mp;
 
  for(;;) {
    pthread_mutex_lock(&lock);
    while (head == NULL) {
      pthread_cond_wait(&has_product, &lock);
    }
    mp = head;
    head = mp->next;
    pthread_mutex_unlock(&lock);
    printf("Consume %d\n", mp->num);
    free(mp);
    sleep(rand() % 5);
  }
}
 
void* producer(void *p)
{
  struct msg *mp;
 
  for(;;) {
    mp = (struct msg *)malloc(sizeof(*mp));
    pthread_mutex_lock(&lock);
    mp->next = head;
    mp->num = rand() % 1000;
    head = mp;
    printf("Product %d\n", mp->num);
    pthread_mutex_unlock(&lock);
    pthread_cond_signal(&has_product);
    sleep(rand() % 5);
  }
}
 
int main()
{
  pthread_t pid, cid;
  srand(time(NULL));
 
  pthread_create(&pid, NULL, producer, NULL);
  pthread_create(&cid, NULL, consumer, NULL);
 
  pthread_join(pid, NULL);
  pthread_join(cid, NULL);
 
  return 0;
}

延伸 · 閱讀

精彩推薦
  • C/C++學習C++編程的必備軟件

    學習C++編程的必備軟件

    本文給大家分享的是作者在學習使用C++進行編程的時候所用到的一些常用的軟件,這里推薦給大家...

    謝恩銘10102021-05-08
  • C/C++c++ 單線程實現同時監聽多個端口

    c++ 單線程實現同時監聽多個端口

    這篇文章主要介紹了c++ 單線程實現同時監聽多個端口的方法,幫助大家更好的理解和學習使用c++,感興趣的朋友可以了解下...

    源之緣11542021-10-27
  • C/C++深入理解goto語句的替代實現方式分析

    深入理解goto語句的替代實現方式分析

    本篇文章是對goto語句的替代實現方式進行了詳細的分析介紹,需要的朋友參考下...

    C語言教程網7342020-12-03
  • C/C++C語言實現電腦關機程序

    C語言實現電腦關機程序

    這篇文章主要為大家詳細介紹了C語言實現電腦關機程序,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下...

    xiaocaidayong8482021-08-20
  • C/C++C語言中炫酷的文件操作實例詳解

    C語言中炫酷的文件操作實例詳解

    內存中的數據都是暫時的,當程序結束時,它們都將丟失,為了永久性的保存大量的數據,C語言提供了對文件的操作,這篇文章主要給大家介紹了關于C語言中文件...

    針眼_6702022-01-24
  • C/C++C/C++經典實例之模擬計算器示例代碼

    C/C++經典實例之模擬計算器示例代碼

    最近在看到的一個需求,本以為比較簡單,但花了不少時間,所以下面這篇文章主要給大家介紹了關于C/C++經典實例之模擬計算器的相關資料,文中通過示...

    jia150610152021-06-07
  • C/C++C++之重載 重定義與重寫用法詳解

    C++之重載 重定義與重寫用法詳解

    這篇文章主要介紹了C++之重載 重定義與重寫用法詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下...

    青山的青6062022-01-04
  • C/C++詳解c語言中的 strcpy和strncpy字符串函數使用

    詳解c語言中的 strcpy和strncpy字符串函數使用

    strcpy 和strcnpy函數是字符串復制函數。接下來通過本文給大家介紹c語言中的strcpy和strncpy字符串函數使用,感興趣的朋友跟隨小編要求看看吧...

    spring-go5642021-07-02
主站蜘蛛池模板: 无限在线看免费视频大全 | 亚洲精品国产国语 | 日产中文乱码卡一卡二 | 1024日韩基地| 国产性做久久久久久 | 国内在线播放 | 美女叽叽 | 午夜尤物| 久久高清一级毛片 | 国产精品99久久久 | 啊哈用力cao我 | 国产无限免费观看黄网站 | 超级碰碰青草免费视频92 | 波多野结衣作品在线观看 | 欧美不卡一区二区三区免 | 色综合久久六月婷婷中文字幕 | www.精品在线 | 情乱奶水欲 | 大学生情侣在线 | yellow视频在线观看免费 | 4虎影院在线观看 | 亚洲AV中文字幕无码久久 | 91在线 一区 二区三区 | 国亚洲欧美日韩精品 | jux539原千岁在线播放 | 亚洲冬月枫中文字幕在线看 | 国产日韩视频一区 | 色天天色综合 | 狠狠的撞击发泄h | 性欧美f | 黄色大片免费网站 | 国产成人精品日本亚洲网址 | 风间由美理论片在线观看 | 91亚洲一区二区在线观看不卡 | 国产第一福利视频导航在线 | 免费高清www动漫视频播放器 | 国产51 | 免费特黄视频 | 爱情岛永久成人免费网站 | 亚洲娇小性hd | 无限资源在线观看播放 |