// Attached: HW_11
// File: HW_11
// Programmer: Elaine Torrez
// Class: CMPR 121

#include <iostream>
#include <fstream>
#include <cmath>
#include <ctime>
#include <thread>
using namespace std;

void writeRoots();
void writeSquares();

int main()
{
    clock_t start;
    clock_t end;
    double runtimeWithoutThreads;
    double runtimeWithThreads;

    cout << "main: startup\n\n";

    start = clock();

    cout << "Waiting for file thread\n";
    writeRoots();
    writeSquares();

    end = clock();

    runtimeWithoutThreads = static_cast<double>(end - start) / CLOCKS_PER_SEC;

    cout << "\nmain: done\n";
    cout << "Runtime without threads = " << runtimeWithoutThreads << " seconds.\n\n";

    start = clock();

    cout << "main: startup\n\n";
    cout << "Waiting for file thread\n";

    thread firstThread(writeRoots);
    thread secondThread(writeSquares);

    firstThread.join();
    secondThread.join();

    end = clock();

    runtimeWithThreads = static_cast<double>(end - start) / CLOCKS_PER_SEC;

    cout << "\nmain: done\n";
    cout << "Runtime with threads = " << runtimeWithThreads << " seconds.\n\n";

    if (runtimeWithThreads < runtimeWithoutThreads)
    {
        cout << "The multithreaded version saved time.\n";
    }
    else
    {
        cout << "The multithreaded version did not save time.\n";
    }

    return 0;
}

void writeRoots()
{
    ofstream outputFile;
    int number;

    outputFile.open("roots.txt");

    cout << "Writing 1,000,000 square roots to a file\n";

    for (number = 1; number <= 1000000; number++)
    {
        outputFile << "The square root of " << number << " is "
                   << sqrt(number) << endl;
    }

    outputFile.close();

    cout << "The square roots are ready.\n";
}

void writeSquares()
{
    ofstream outputFile;
    int number;
    long long square;

    outputFile.open("squares.txt");

    cout << "Squaring 1000000 numbers\n";

    for (number = 1; number <= 1000000; number++)
    {
        square = static_cast<long long>(number) * number;

        outputFile << number << " squared is " << square << endl;
    }

    outputFile.close();

    cout << "The squares are ready.\n";
}