-1

Hey so I am having an issue with the code as now it is not displaying things at correct percentages, whenever I use more than 2 threads the percentages tend to go over 100% whenever it prints out progress which is not what I want it to do at all. What I want is for at the end for it to add up to 100% or at least not go over it before the program finishes. Any and all help is much appreciated.

#include <chrono>
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>

// Import things we need from the standard library
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using std::cout;
using std::endl;

typedef std::chrono::steady_clock the_clock;

const int alpha = 1920;
const int beta = 1200;

const int MAX_ITERATIONS = 500;

std::atomic<double> progress;
std::atomic_bool progressDone = false;
std::mutex locking;
std::condition_variable conditionMet;
std::atomic_int partsDone = 0;
int noOfThreads;

void progress_bar() {

    while (!progressDone) {

        cout << "Current Progress is at: " << progress.load() << "%\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(100));

    }

    cout << "We are finished!";

}

void compute(double start, double finish)
{
    for (int y = start; y < finish; ++y)
    {
        for (int x = 0; x < alpha; ++x)
        {
            progress = progress + double(((1.0 / (alpha*beta)) * 100.0)/noOfThreads);
        }
    }
    partsDone += 1;
}


int main(int argc, char *argv[])
{
    cout << "Please wait..." << endl;

    cout << "How many threads do you want to use?: ";
    std::cin >> noOfThreads;

    // Start timing
    std::vector<std::thread*> threads;
    the_clock::time_point start = the_clock::now();

    std::thread progressive(progress_bar);

    for (int slice = 0; slice < noOfThreads; slice++) {

        threads.push_back(new std::thread(compute, alpha * double(slice / noOfThreads), beta * double((slice + 1.0) / noOfThreads)));

    }

    for (std::thread* t : threads) {

        t->join();
        delete t;

    }

    if (partsDone == noOfThreads) {

        progressDone = true;

    }

    progressive.join();

    the_clock::time_point end = the_clock::now();

    auto time_taken = duration_cast<milliseconds>(end - start).count();
    cout << "Computing the program took " << time_taken << " ms." << endl;

    std::this_thread::sleep_for(milliseconds(3000));

    return 0;
}

Also if anyone has tips for optimizing or speeding up the program, that is also very much appreciated.

Kitso
  • 49
  • 5

0 Answers0