-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
86 lines (72 loc) · 2.47 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"fmt"
"sync"
"sync/atomic"
)
// conversionFactor is used to scale values by 1000 to preserve precision during float64 to int64 conversion.
const conversionFactor int64 = 1000
type Account struct {
balance int64 // Balance stored in "scaled integer format" (e.g., 50.123 is stored as 50123)
}
// GetRawBalance returns the balance as an int64 value in its scaled format (internal representation).
func (a *Account) GetRawBalance() int64 {
return atomic.LoadInt64(&a.balance)
}
// GetBalance returns the balance as a float64 value for external use (converted from the scaled format).
func (a *Account) GetBalance() float64 {
return float64(a.GetRawBalance()) / float64(conversionFactor)
}
// Deposit adds an amount (in float64) to the account balance.
func (a *Account) Deposit(amount float64) {
scaleAmount := int64(amount * float64(conversionFactor))
atomic.AddInt64(&a.balance, scaleAmount)
}
// Withdraw attempts to subtract an amount (in float64) from the account balance atomically.
// Returns true if the withdrawal is successful, or false if there are insufficient funds.
func (a *Account) WithDraw(amount float64) bool {
scaleAmount := int64(amount * float64(conversionFactor))
for {
currentBalance := a.GetRawBalance()
if currentBalance < scaleAmount {
return false
}
if atomic.CompareAndSwapInt64(¤tBalance, currentBalance, scaleAmount) {
return true
}
}
}
func main() {
var wg sync.WaitGroup
account := &Account{}
numGoroutines := 5
// Goroutines for deposits
for i := 0; i < numGoroutines; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
amount := float64(id) * 10.25
beforeBalance := account.GetBalance()
account.Deposit(amount)
afterBalance := account.GetBalance()
fmt.Printf("->[%d]: Deposited %.2f | Before: %.2f, After: %.2f\n", id, amount, beforeBalance, afterBalance)
}(i)
}
// Goroutines for withdrawals
for i := 0; i < numGoroutines; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
amount := float64(id) * 15.50
beforeBalance := account.GetBalance()
if success := account.WithDraw(amount); success {
afterBalance := account.GetBalance()
fmt.Printf("<-[%d]: Successfully withdrew %.2f | Before: %.2f, After: %.2f\n", id, amount, beforeBalance, afterBalance)
} else {
fmt.Printf("<-[%d]: Failed to withdraw %.2f (Insufficient funds) | Balance: %.2f\n", id, amount, beforeBalance)
}
}(i)
}
wg.Wait()
fmt.Printf("Final account balance: %.2f\n", account.GetBalance())
}