// 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>

using namespace std;

#include <QtCore/QThread>
#include <QtCore/QTime>

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;

class Processor : public QThread
{
private:
    Data *d;
protected:
    virtual void run();
public:
    Processor(Data *d);
};

Processor::Processor(Data *d)
{
    this->d = d;
}

void Processor::run()
{
    // simulate a lot of work that takes 0.1 second
    string s = d->GetS();
    QThread::msleep(100);
    d->SetS(s + "X");
}

typedef QThread *QThreadPtr;

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
    QTime tim;
    tim.start();;
    int k = 0;
    for(int i = 0; i < njobs / nthreads; i++)
    {
        // create threads
        QThreadPtr *t = new QThreadPtr[nthreads];
        for(int j = 0; j < nthreads; j++)
        {
            t[j] = new Processor(d[k]);
            k++;
        }
        // start threads
        for(int j = 0; j < nthreads; j++)
        {
            t[j]->start();
        }
        // wait for threads to complete
        for(int j = 0; j < nthreads; j++)
        {
            t[j]->wait();
            delete t[j];
        }
        delete[] t;
    }
    int dt = tim.elapsed();
    cout << njobs << " jobs executing in " << nthreads << " threads : " << fixed << setprecision(1) << (dt / 1000.0) << " seconds" << endl;;
    // check data
    for(int i = 0; i < njobs; i++)
    {
        if(d[i]->GetS() != "XX") cout << "Ooops" << endl;
        delete d[i];
    }
    delete[] d;
}

void realmain()
{
    test(256, 1);
    test(256, 2);
    test(256, 4);
    test(256, 8);
    test(256, 16);
    test(256, 32);
    test(256, 64);
}
