package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

type Account struct {
	balance int
}

func transfer(amount int, flag *int32, from *Account, to *Account, group *sync.WaitGroup) {

	for !atomic.CompareAndSwapInt32(flag, 0, 1) {
	}

	if from.balance >= amount {
		from.balance -= amount
		to.balance += amount
	}

	atomic.StoreInt32(flag, 0)

	group.Done()
}

func main() {

	account1 := Account{100}
	account2 := Account{100}

	var group sync.WaitGroup
	var atomicFlag int32

	for i := 0; i < 100; i++ {
		group.Add(2)
		go transfer(1, &atomicFlag, &account1, &account2, &group)
		go transfer(1, &atomicFlag, &account2, &account1, &group)
	}
	group.Wait()
	fmt.Println("Account1 Balance = $", account1.balance)
	fmt.Println("Account2 Balance = $", account2.balance)
}
