linux下多執行緒程式設計入門(二)

2021-10-23 15:26:56 字數 2224 閱讀 1999

上一節中,從輸出的數字分布,可以看出是**多執行緒輪流執行的,但是我們並不知道對應數字是哪乙個執行緒輸出的,這一節我們通過學習往執行緒中傳引數 ,以此區分執行緒。

#include

#include

#include

void

*test

(void

* args)

//傳入的引數是 void *型別

intmain()

輸出結果

分析輸出結果知道th1和th2輪流輸出。

然後我們就可以使用多執行緒同時計算

#include

#include

#include

int arr[

5000];

int s1=0;

int s2=0;

void

*test

(void

* args)

//傳入的引數是 void *型別

void

*test2

(void

* args)

//傳入的引數是 void *型別

intmain()

pthread_t th2;

pthread_t th1;

pthread_create

(&th1,

null

,test,

null);

//第四個引數:輸出字串th

pthread_create

(&th2,

null

,test2,

null);

pthread_join

(th1,

null);

//等待執行緒th執行完

pthread_join

(th2,

null);

//等待執行緒th1執行完

printf

("s1=%d\n"

,s1)

;printf

("s2=%d\n"

,s2)

;printf

("s1+s2=%d\n"

,s1+s2)

;printf

("\n");

return0;

}

上面的**意思是 計算陣列arr[5000]的累加,其中執行緒1計算前2500個累加,執行緒2計算後2500個的累加,然後兩者相加。

但是這段**並沒有發揮多執行緒的優勢,而且有重複**片段,我們可以做如下修改:

#include

#include

#include

typedef

struct

my_args;

int arr[

5000];

void

*test

(void

* args)

//傳入的引數是 void *型別

intmain()

pthread_t th2;

pthread_t th1;

my_args args1=

; my_args args2=

;pthread_create

(&th1,

null

,test,

&args1)

;pthread_create

(&th2,

null

,test,

&args2)

;pthread_join

(th1,

null);

//等待執行緒th執行完

pthread_join

(th2,

null);

//等待執行緒th1執行完

int s1=args1.result;

int s2=args2.result;

printf

("s1=%d\n"

,s1)

;printf

("s2=%d\n"

,s2)

;printf

("s1+s2=%d\n"

,s1+s2)

;printf

("\n");

return0;

}

上面這個**直接傳入結構體的位址,我們以後遇到類似重複高的**都可以用結構體替代。

Linux系統下的多執行緒程式設計入門二

修改執行緒的屬性 在上一節的例子裡,我們用pthread create函式建立了乙個執行緒,在這個執行緒中,我們使用了預設引數,即將該函式的第二個引數設為null。的確,對大多數程式來說,使用預設屬性就夠了,但我們還是有必要來了解一下執行緒的有關屬性。關於執行緒的繫結,牽涉到另外乙個概念 輕程序 l...

linux下多執行緒程式設計入門(三)

前面兩節粗略學習了一下多執行緒程式設計,這一節我們來了解一下鎖的概念。由於多執行緒之間是併發執行的,而系統排程又是隨機的,因此在寫多執行緒程式時會出現很多問題,這時就免不了要用到各種鎖機制來保證執行緒安全且按我們的意願正確執行。當多個執行緒同時讀寫同一塊 區的時候,就出現很多問題。比如初始i 0 我...

Linux 多執行緒程式設計入門

建立執行緒 intpthread create pthread t restrict thread,const pthread attr t restrict attr,void start routine void void restrict arg 引數 thread 輸出執行緒id attr ...