小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

C 多線程1——pthread

 印度阿三17 2021-02-13

一、多核時(shí)代

隨著數(shù)字IC工藝的提升,單核性能越來越高,但隨之來的是功率密度增大,芯片發(fā)熱嚴(yán)重,要進(jìn)一步提升性能,很自然會(huì)想到C多核。將計(jì)算任務(wù)分配到不同的cpu,最后將結(jié)果整合,完成多核并行。

二、C\C 的多線程

C提供了很方便的多線程庫,最基本的是pthread庫,C 里有thread庫(調(diào)用起來更加方便),還有omp庫(不必自己設(shè)置線程,已封裝好),接下來將介紹C pthread庫的應(yīng)用實(shí)例,這些實(shí)例能夠很方便移植到不同的應(yīng)用中。omp庫的實(shí)例可參看C openmp并行計(jì)算實(shí)例。

三、實(shí)例

pthread的實(shí)例參考了B站up主“正月點(diǎn)燈”的教學(xué)視頻,講得非常通俗易懂。

假設(shè)我們有一個(gè)數(shù)組arr[],長度為1億,元素大小為0~4的隨機(jī)數(shù),我們需要計(jì)算它的和。

為此我們可以用兩個(gè)線程,一個(gè)線程計(jì)算前5千萬個(gè)元素之和,另一個(gè)線程計(jì)算后5千萬個(gè)元素之和,最后兩種相加。

順便比較單線程的耗時(shí),代碼如下:

#include <stdio.h>
#include <stdlib.h> 
#include <pthread.h>
#include <time.h> 
#include <omp.h>
#define MAX_SIZE 100000000
int* arr;
// 定義數(shù)據(jù)結(jié)構(gòu),用來傳遞參數(shù)
typedef struct{
 int first;
 int last;
 int result;
}MY_ARGS;
//定義函數(shù),給多線程調(diào)用
void* myfunc(void* args){
 int i;
 int s=0;
 MY_ARGS* my_args = (MY_ARGS*) args;
 int first = my_args->first;
 int last = ?my_args->last;

 for(i=first;i<last;i  ){
 s=s arr[i];
 }
 my_args -> result = s;
 return ?NULL;
}

int main(){
  pthread_t th1;
  pthread_t th2;

  int i;
  arr = malloc(sizeof(int) * MAX_SIZE);
  int mid = MAX_SIZE/2;
  for(i=0;i<MAX_SIZE;i  ){
   arr[i]=rand()%5;
  }

 MY_ARGS args1 = {0,mid,0};
 MY_ARGS args2 = {mid,MAX_SIZE,0};
 //1.pthread running time 
 clock_t start,end;
 start = clock();
 pthread_create(&th1,NULL,myfunc,&args1);
 pthread_create(&th2,NULL,myfunc,&args2);
 pthread_join(th1,NULL);
 pthread_join(th2,NULL);
 int s = args1.result args2.result;
 end = clock();

 printf("s  = %d\n",s);
 printf("thread2 time : %ld\n",end-start);

 // 2.single running time
 start = clock();
 s = 0;
 for(i=0;i<MAX_SIZE;i  ){
 s = s  arr[i];
 }
 end = clock(); 

 printf("s  = %d\n",s);
 printf("single time:  %ld\n",end-start);


 // 3.omp running time
 start = clock();
 s = 0;
 omp_set_num_threads(2);
 #pragma omp parallel 
 {
 #pragma omp for reduction( :s)
 for(i=0;i<MAX_SIZE;i  ){
 s = s  arr[i];
 }
 }
 end = clock(); 

 printf("s  = %d\n",s);
 printf("omp time:  %ld\n",end-start);

 return 0;

}

代碼比較了pthread2線程,單線程,omp2線程的結(jié)果:

pth1.jpg

可見兩個(gè)線程,甚至還有可能變慢,可能的原因是這里的數(shù)據(jù)連續(xù)分布,gcc的優(yōu)化已經(jīng)很極致。如果兩個(gè)任務(wù)比較獨(dú)立,并行的效果會(huì)更明顯。這里只是給個(gè)pthread應(yīng)用的實(shí)例。

另見C 多線程——pthread

來源:https://www./content-1-856001.html

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多