I recently read the book "the D programming language" and wanted to try out a few of the multithreaded examples pointed out in this book. I tried to write a version of the bank account example using the atomicOp from core.atomic. But when I compile it, it never finishes, it just gets stuck in a endless loop inside atomic.d I think.
Here is the code:

import std.stdio;
import std.concurrency;

enum Messages {
        GO
}

shared class Account {
        private float amount = 0;
                
        float getAmount() const {
                return amount;
        }
                
        void change(float change){
                atomicOp!"+="(amount,change);
        }
}

shared Account bank = null;
        
void otherThread(Tid father){
        send(father,Messages.GO);
        for(int i=0;i<1000;i++)
                bank.change(-100);
}

void main(string[] args)
{
        bank = new Account();
        spawn(&otherThread,thisTid);
        receiveOnly!(Messages)();
        for(int i=0;i<1000;i++)
                bank.change(+100);
        writefln("Program finished. Amount is %s",bank.getAmount());
}

If you could please point out what I did wrong I would be very glad. If I did not do anything wrong, I don't quite understand whats the exact problem because the code inside atomic.d looks good (at least at my level of understanding)

--
Kind Regards
Benjamin Thaut

Reply via email to