Fixed final code for multithread

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

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

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();
t2->wait();
t3->wait();

supposed to get a sum of 100, issue below occurs when you don't use QMutex:
t1 t2 t3
r=5;
x=35;
y=45;
r=19;
x=74;
sum=
74+45
119

class Account
{
private:
QMutex mu;
QWaitCondition cond;
int balance;
public:
Account() { balance=100; }
void deposit(int d)
{
mu.lock();
balance += d;
cond.wakeAll();
mu.unlock();
}
void withdraw(int w)
{
mu.lock();
while (balance<w)
{
cond.wait(&mu); // temp release lock, inform me while the condition has changed
}
balance-=w;
mu.unlock();
}
void print()
{
mu.lock();
cout << balance << endl;
mu.unlock();
}
}; //Account

run()
{
int flag=0;
while (flag==0)
{
if (will)
{
a->withdraw(1000);
flag = 1;
}
else
{
a->deposit(1000);
flag = 1;
}
} //while
} //run

Account *a=new Account();
MyThread *mom=new ...
MyThread *will=...
mom->start();
will->start();

Alumni Liaison

EISL lab graduate

Mu Qiao