Revision as of 15:02, 3 November 2010 by Jmulesa (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

class Data
{
public:
Data(int a, int b)
{
x=a;
y=b;
}
void f() //make atomic
{
mu.lock(); //fix sharing issue
int r=rand()%100;
x+=r;
y-=r;
mu.unlock(); //fix sharing issue
}
int sum() //make atomic
{
mu.lock(); //fix sharing issue
return(x+y);
mu.unlock(); //fix sharing issue
}
private:
QMutex mu; //mutually exclusive
int x;
int y;
};

Data *d = new Data(50,50);
for (int i=0;i<100;i++)
{
d->f();
cout << d->sum() << endl;
}


what's the output? ans: 100

class MyThread : public QThread
{
public:
MyThread(Data *x) //change to (Data x)
{
d=x;
}
void run()
{
for(int i=0;i<100;i++)
{
d->f(); //change to d.f();
cout << d->sum() << endl;
}
}
Data *d; //change to Data d;
};

main(...)
{
Data *d=new Data(50,50);
MyThread *t1=new MyThread(d);
MyThread *t2=new MyThread(d);
MyThread *t3=new MyThread(d);
t1->start();
t2->start();
t3->start();
t1->wait(); // join() in java
t2->wait();
t3->wait();
}

t1 t2 t3
r=7
x=57
y=43
r=11
x=68
sum
(68+43)
=111

//changes will fix issue since data is not shared then

Alumni Liaison

Meet a recent graduate heading to Sweden for a Postdoctorate.

Christine Berkesch