创建另一个循环并以并行线程

时间:2016-10-19 17:11:44

标签: c++ multithreading

这是我进行并行编程的第一周,我似乎无法弄清楚这一点。当我调试程序时,它停留在“生成数字......”。我认为解决这个问题的唯一方法是为自己创建另一个循环并在并行线程中运行它。你能帮我吗?

#include <iostream>
#include <cstdlib>
#include <climits>
#include <ctime>
#include <time.h>
#include <Windows.h>

using namespace std;

const int NSIZE = INT_MAX / 5;

void gen_numbers (float numbers[], int how_many);
float gen_rand(int min, int max);
float sum(float array[], int num_elements);


float numbers[NSIZE];

int main()
{
    unsigned int seed = time(0);
    srand(seed);

    __int64 start1 = GetTickCount();

    cout << "Generating numbers..." << flush;
    gen_numbers(numbers, NSIZE);
    cout << "done." << endl;

    cout << "Summing the numbers..." << flush;
    float answer = sum(numbers, NSIZE);
    cout << "done" << endl;
    __int64 end1 = GetTickCount();

    cout << "Total time: " << end1 - start1 << endl;

    cout << "Answer: " << answer << endl;
    system("pause");
    return 0;
}

float sum(float array[], int num_elements)
{
    float nsum = 0.0;
    #pragma omp parallel for reduction(+:nsum)
    for (int i = 0; i < num_elements; i++)
    {
        nsum += array[i];
    }
    return nsum;
}

void gen_numbers(float numbers[], int how_many)
{
    #pragma omp parallel for
    for (int i = 0; i < how_many; i++)
    {
        numbers[i] = gen_rand(0, 10);
    }
}

float gen_rand(int min, int max)
{
    return(min + static_cast <float> (rand()) /
        (static_cast <float> (RAND_MAX / (max - min))));
}

1 个答案:

答案 0 :(得分:-1)

要调试程序,您可以在每个表达式后使用cout。 因此,您将知道停止的位置以及每一步的数据。