Multithreading Parallel Computing data sum C language Demo

Source: Internet
Author: User

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

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.