// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
#include <iostream>
#include <iomanip>
#include <string>
#include <thread>
#include <chrono>

using namespace std;
using namespace std::chrono;

class Data
{
private:
    string s;
public:
    Data(string s);
    string GetS();
    void SetS(string s);
};

Data::Data(string s)
{
    this->s = s;
}

string Data::GetS()
{
    return s;
}

void Data::SetS(string s)
{
    this->s = s;
}

typedef Data *DataPtr;

void run(Data *d)
{
    // simulate a lot of work that takes 0.1 second
    string s = d->GetS();
    this_thread::sleep_for(milliseconds(100));
    d->SetS(s + "X");
}

typedef thread *thread_ptr;

void test(int njobs, int nthreads)
{
    // setup data
    DataPtr *d = new DataPtr[njobs];
    for(int i = 0; i < njobs; i++)
    {
        d[i] = new Data("X");
    }
    // process
    time_point<system_clock> t1 = system_clock::now();
    int k = 0;
    for(int i = 0; i < njobs / nthreads; i++)
    {
        // create and start threads
        thread_ptr *t = new thread_ptr[nthreads];
        for(int j = 0; j < nthreads; j++)
        {
            t[j] = new thread(run, d[k]);
            k++;
        }
        // wait for threads to complete
        for(int j = 0; j < nthreads; j++)
        {
            t[j]->join();
            delete t[j];
        }
        delete[] t;
    }
    time_point<system_clock> t2 = system_clock::now();
    duration<double> dt = t2 - t1;
    cout << njobs << " jobs executing in " << nthreads << " threads : " << fixed << setprecision(1) << dt.count() << " seconds" << endl;;
    // check data
    for(int i = 0; i < njobs; i++)
    {
        if(d[i]->GetS() != "XX") cout << "Ooops" << endl;
        delete d[i];
    }
    delete[] d;
}

int main()
{
    test(256, 1);
    test(256, 2);
    test(256, 4);
    test(256, 8);
    test(256, 16);
    test(256, 32);
    test(256, 64);
    return 0;
}

