电竞比分网-中国电竞赛事及体育赛事平台

分享

C 多線程1——pthread

 印度阿三17 2021-02-13

一、多核時代

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

二、C\C 的多線程

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

三、實例

pthread的實例參考了B站up主“正月點燈”的教學視頻,講得非常通俗易懂。

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

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

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

#include <stdio.h>
#include <stdlib.h> 
#include <pthread.h>
#include <time.h> 
#include <omp.h>
#define MAX_SIZE 100000000
int* arr;
// 定義數(shù)據(jù)結構,用來傳遞參數(shù)
typedef struct{
 int first;
 int last;
 int result;
}MY_ARGS;
//定義函數(shù),給多線程調用
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線程的結果:

pth1.jpg

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

另見C 多線程——pthread

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

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

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多