多線程並行計算資料總和 C語言demo

來源:互聯網
上載者:User

標籤:clu   system   thread   地址   std   oid   div   read   線程   

多線程計算整型數組資料總和:

#include <stdio.h>#include <stdlib.h>#include <Windows.h>#include<process.h>#include <time.h>#define N 1024struct Myinfo{    int *pstart;//開始地址    int length;//長度    int id;//線程編號    int sum;//儲存資料的和};void  add(void *p) //void *p可以儲存任何類型的指標{    struct Myinfo *pinfo = p;    for (int i = 0; i < pinfo->length;i++)    {        pinfo->sum += pinfo->pstart[i];    }    printf("\n線程%d計算的結果%d", pinfo->id, pinfo->sum);}void main(){    time_t ts;    unsigned int num = time(&ts);//傳遞地址    srand(num);    int data[N] = { 0 };
   // 進行賦值
for (int i = 0; i < N; i++) { data[i] = rand() % 1000; //printf("%4d", data[i] = rand() % 1000); } int sum = 0;
   //計算總和
for (int i = 0; i < N; i++) { sum += data[i]; } printf("\n總和=%d", sum); struct Myinfo info[8] = { 0 }; for (int i = 0; i < 8;i++) { info[i].id = i; info[i].length = N / 8; info[i].sum = 0; info[i].pstart = data + i*N / 8; //注意這裡地址的移動 _beginthread(add, 0, &info[i]); } system("pause"); int lastsum=0; for (int i = 0; i < 8;i++) { lastsum += info[i].sum; } printf("\n多線程總和=%d", lastsum); system("pause");}

在此也可以結合隊列來使用

 

多線程並行計算資料總和 C語言demo

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.