How to prevent critical section access with atomics in C++

  atomicity, c++, multithreading

I have a program where 4 threads are doing random transactions between two "bank accounts" , at every 100th transaction per account a interest of 5% should be added to account.

This is a exercise for school I have to do, and in previous lesson we used mutexe’s which seemed very straightforward in locking a section of code.
Now we have to do same thing but using atomic’s.

My problem is that currently more than one thread can enter addIntreset function and interest can be added multiple times.

this is part of 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;       
    }

Source: Windows Questions C++

LEAVE A COMMENT