awesome-patterns/concurrency/read_struct_props/main.go

70 lines
988 B
Go
Raw Normal View History

package main
import (
2018-02-02 09:06:53 +03:00
"fmt"
"time"
)
// package shows if read/write concurrently via struct
type Person struct {
2018-02-02 09:06:53 +03:00
Name string
}
2018-02-02 09:06:53 +03:00
// simulate write operation for struct property which is name is this case
func (p *Person) updateName1() {
for {
2018-02-02 09:06:53 +03:00
p.Name = "Dummy Name 1"
}
}
2018-02-02 09:06:53 +03:00
// simulate write operation for struct property which is name is this case
func (p *Person) updateName2() {
for {
2018-02-02 09:06:53 +03:00
p.Name = "Dummy Name 2"
}
}
2018-02-02 09:06:53 +03:00
func (p *Person) printName() {
for {
2018-02-02 09:06:53 +03:00
fmt.Println("Current Name Is : ", p.Name)
}
}
var m = map[string]int{"a": 1}
func main() {
p := &Person{Name: "James"}
2018-02-02 09:06:53 +03:00
go p.updateName1()
go p.updateName2()
go p.printName()
// SimulateConcurrentReadWriteMap()
time.Sleep(2 * time.Second)
}
func SimulateConcurrentReadWriteMap() {
// Concurrent read is ok, but write is not
go Read()
go Write()
time.Sleep(6 * time.Second)
}
func Read() {
for {
read()
}
}
func Write() {
for {
write()
}
}
func read() {
_ = m["a"]
}
func write() {
m["b"] = 2
}