Multi-thread parallel computing data sum C language demo, parallel computing demo
The sum of integer array data calculated using multiple threads:
# Include <stdio. h> # include <stdlib. h> # include <Windows. h> # include <process. h> # include <time. h> # define N 1024 struct Myinfo {int * pstart; // start address int length; // length int id; // thread number int sum; // The sum of the stored data}; void add (void * p) // void * p can save any type of pointer {struct Myinfo * pinfo = p; for (int I = 0; I <pinfo-> length; I ++) {pinfo-> sum + = pinfo-> pstart [I];} printf ("\ n thread % d calculation result % d", pinfo-> id, pinfo-> sum);} void main () {time_t ts; unsigned int num = time (& ts); // transfer address srand (num); int data [N] = {0 };
// Assign a value for (int I = 0; I <N; I ++) {data [I] = rand () % 1000; // printf ("% 4d ", data [I] = rand () % 1000);} int sum = 0;
// Calculate the sum of for (int I = 0; I <N; I ++) {sum + = data [I];} printf ("\ n sum = % 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; // note the _ beginthread (add, 0, & info [I]);} system ("pause "); int lastsum = 0; for (int I = 0; I <8; I ++) {lastsum + = info [I]. sum;} printf ("\ n total of multiple threads = % d", lastsum); system ("pause ");}
This can also be used in combination with queues.