首页 > 代码库 > 多线程并行计算数据总和 C语言demo

多线程并行计算数据总和 C语言demo

多线程计算整型数组数据总和:

#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include<process.h>
#include <time.h>
#define N 1024

struct 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