forked from ardanlabs/gotraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example1.go
80 lines (65 loc) · 1.67 KB
/
example1.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
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// Sample program to show a more complicated race condition using
// an interface value. This produces a read to an inteface value after
// a partial write.
package main
import "fmt"
// Speaker allows for speaking behavior.
type Speaker interface {
Speak() bool
}
// Ben is a person who can speak.
type Ben struct {
name string
}
// Speak allows Ben to say hello. It returns false if the method is
// called through the interface value after a partial write.
func (b *Ben) Speak() bool {
if b.name != "Ben" {
fmt.Printf("Ben says, \"Hello my name is %s\"\n", b.name)
return false
}
return true
}
// Jerry is a person who can speak.
type Jerry struct {
name string
}
// Speak allows Jerry to say hello. It returns false if the method is
// called through the interface value after a partial write.
func (j *Jerry) Speak() bool {
if j.name != "Jerry" {
fmt.Printf("Jerry says, \"Hello my name is %s\"\n", j.name)
return false
}
return true
}
func main() {
// Create values of type Ben and Jerry.
ben := Ben{"Ben"}
jerry := Jerry{"Jerry"}
// Assign the pointer to the Ben value to the interface value.
person := Speaker(&ben)
// Have a goroutine constantly assign the pointer of
// the Ben value to the interface.
go func() {
for {
person = &ben
}
}()
// Have a goroutine constantly assign the pointer of
// the Jerry value to the interface.
go func() {
for {
person = &jerry
}
}()
// Keep calling the Speak method against the interface
// value until we have a race condition.
for {
if !person.Speak() {
break
}
}
}