-
Notifications
You must be signed in to change notification settings - Fork 0
/
goroutine_test.go
86 lines (65 loc) · 1.39 KB
/
goroutine_test.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 golang_goroutine
import (
"fmt"
"sync"
"testing"
"time"
)
func RunGoroutine() {
fmt.Println("Run Goroutine!")
}
func TestCreateGoroutine(t *testing.T) {
go RunGoroutine()
fmt.Println("Error message!")
time.Sleep(1 * time.Nanosecond)
}
func DisplayName(number int) {
fmt.Println("Display", number)
}
func TestManyGoroutine(t *testing.T) {
for i := 0; i < 100000; i++ {
go DisplayName(i)
}
time.Sleep(5 * time.Second)
}
type UserBalance struct {
sync.Mutex
Name string
Balance int
}
func (user *UserBalance) Lock() {
user.Mutex.Lock()
}
func (user *UserBalance) Unlock() {
user.Mutex.Unlock()
}
func (user *UserBalance) Change(amount int) {
user.Balance = user.Balance + amount
}
func Transfer(user1 *UserBalance, user2 *UserBalance, amount int) {
user1.Lock()
fmt.Println("Lock", user1.Name)
user1.Change(amount)
time.Sleep(1 * time.Second)
user2.Lock()
fmt.Println("Lock", user2.Name)
user2.Change(amount)
time.Sleep(1 * time.Second)
user1.Unlock()
user2.Unlock()
}
func TestDeadlock(t *testing.T) {
user1 := UserBalance{
Name: "Batman",
Balance: 1000000,
}
user2 := UserBalance{
Name: "Spiderman",
Balance: 1000000,
}
go Transfer(&user1, &user2, 100000)
go Transfer(&user2, &user1, 200000)
time.Sleep(2 * time.Second)
fmt.Println("User", user1.Name, "Balance", user1.Balance)
fmt.Println("User", user2.Name, "Balance", user2.Balance)
}