lundi 22 juillet 2019

How do I store multiple thread function results to one array or vector

I made a program that found prime numbers within two specified boundaries. It was pretty easy to make and it worked well. The problem was it was just too slow. To fix that I decided to use multiple threads to split up the task. 100 threads would be created if the difference in the boundaries was 100 or over. Each thread would call the function PrimeIterator and have the workload of the difference in boundaries divided by 100. For example: if I entered the start boundary as 100 and the end boundary as 1100, each of the 100 threads would compute 10 numbers to determine if they are primes or not.

Obviously, each of the threads will be running at the same time. I want all the determined prime numbers to be stored in one array. To do this I tried creating 100 different vectors (with a for loop) for each thread to store the numbers in so there wasn't a global array being used by all 100 threads. Hypothetically (never got it to work), after being stored they would be sorted and stored into one array/vector where they can be displayed to the user.

The problem: How do I store values from all 100 threads calling the same function PrimeIterator?

Note: The logic for dividing the workload equally to each thread is not completed and doesn't work. I don't need any help with that part.

Code:

include "stdafx.h"
#include "iostream"
#include <thread>
#include <cmath>
#include <vector>

using namespace std;

bool PrimeNumberChecker(int x);
void PrimeIterator(int x, int y);



static const int num_threads = 99;

int main()
{
    int val1, dividend, divisor, threadIterator1, threadIterator2;
    int x, y, i;
    thread t[num_threads];

    cout << "Enter Start Boundary: ";
    cin >> x;
    cout << "\nEnter End Boundary: ";
    cin >> y;

    val1 = (y - x) / 100;
    dividend = floor(val1);
    divisor = fmod(y-x, 100);


    if (y-x >= 100) 
    {
        thread t2(PrimeIterator, x, divisor);

        for (i = 1; i <= num_threads; i++)
        {
            threadIterator1 = dividend * i;
            threadIterator2 = dividend * (i + 1);

            t[i] = thread(PrimeIterator, threadIterator1, threadIterator2, i);
        }

        t2.join();
        for (int i = 0; i < num_threads; ++i) {
            t[i].join();
        }
    }



    system("pause");
    return 0;
}

bool PrimeNumberChecker(int x) 
{
    int i, t;

    for (i = 2; i <= x ; i++) 
    {

        for (t = 2; t <= x; t++)
        {
            if (i*t == x)
            {
                return false;
            }

        }

    }
    return true;
}


void PrimeIterator(int startBoundary, int endBoundary)
{
    int i;

        for (i = startBoundary; i <= endBoundary; i++)
        {
            if (PrimeNumberChecker(i))
            {


            }
        }


}

Aucun commentaire:

Enregistrer un commentaire