// 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 some work between get and set
    string s = d->GetS();
    QThread::usleep(1);
    d->SetS(s + "X");
}

typedef QThread *QThreadPtr;

void test(int njobs, int nthreads)
{
    // setup data
    Data *d = new Data("");
    // process with shared data
    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);
        }
        // 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;
    }
    cout << nthreads << " threads : expected = " << njobs << ", actual = " << d->GetS().length() << endl;;
    delete d;
}

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