Multithreading computes the sum of integer array data:
#include <stdio.h>#include<stdlib.h>#include<Windows.h>#include<process.h>#include<time.h>#defineN 1024structmyinfo{int*pstart;//Start Address intLength//length intId//Thread Number intSum//Storing Data and};voidAddvoid*P)//void *p can hold any type of pointer{ structMyInfo *pinfo =p; for(inti =0; I < pinfo->length;i++) {pinfo->sum + = pinfo->Pstart[i]; } printf ("\ n Thread%d computed result%d", Pinfo->id, pinfo->sum);}voidMain () {time_t ts; unsignedintnum = time (&ts);//Delivery addresssrand (num); intData[n] = {0 };
To assign a value for(inti =0; i < N; i++) {Data[i]= rand ()% +; //printf ("%4d", data[i] = rand ()%); } intsum =0;
Calculate Sum for(inti =0; i < N; i++) {sum+=Data[i]; } printf ("\ n Total =%d", sum); structMyInfo info[8] = {0 }; for(inti =0; I <8; i++) {info[i].id=i; Info[i].length= N/8; Info[i].sum=0; Info[i].pstart= Data + i*n/8the mobile _beginthread of the address here (add,0, &Info[i]); } System ("Pause"); intlastsum=0; for(inti =0; I <8; i++) {lastsum+=info[i].sum; } printf ("\ n Multithreading sum =%d", lastsum); System ("Pause");}
This can also be combined with a queue to use
Multithreading Parallel Computing data sum C language Demo