Multi-thread parallel computing data sum C language demo, parallel computing demo

Source: Internet
Author: User

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.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.