標籤: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