I have a program where 4 threads are doing random transactions between two "bank accounts", at every 100th transaction per account interest of 5% should be added to the account.
This is an exercise for school I have to do, and in the previous lesson, we used mutexes which seemed very straightforward in locking a section of code. Now we have to do the same thing but using atomics.
My problem is that currently more than one thread can enter addIntreset function and interest can be added multiple times.
this is part of the code where I check if it is 100th transaction
void transfer(Account& acc, int amount, string& thread)
{
++m_iCounter;
withdraw(acc, amount);
if (m_iCounter % 100 == 0)
{
addInterest(thread);
}
}
All threads go through that function and check for % 100 and sometimes more than one thread slips into addInterest. With mutexes I could restrict access here but how do I do it with atomic?
Maybe I could solve this somehow inside addInterest but if so how?
Inside addInterest is following code (if more than 1 thread slip in interest is added multiple times) :
void addInterest(string& thread)
{
float old = m_iBalance.load();
const float interest = 0.05f;
const float amount = old * interest;
while (!m_iBalance.compare_exchange_weak(old, old + amount))
{
//
}
++m_iInterest;
cout << thread << " interest : Acc" << name << " " << m_iCounter << endl;
}