2018-02-01 07:44:47 +03:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2018-02-02 09:06:53 +03:00
|
|
|
"fmt"
|
2018-02-01 07:44:47 +03:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// package shows if read/write concurrently via struct
|
|
|
|
|
|
|
|
type Person struct {
|
2018-02-02 09:06:53 +03:00
|
|
|
Name string
|
2018-02-01 07:44:47 +03:00
|
|
|
}
|
|
|
|
|
2018-02-02 09:06:53 +03:00
|
|
|
// simulate write operation for struct property which is name is this case
|
|
|
|
func (p *Person) updateName1() {
|
2018-02-01 07:44:47 +03:00
|
|
|
for {
|
2018-02-02 09:06:53 +03:00
|
|
|
p.Name = "Dummy Name 1"
|
2018-02-01 07:44:47 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-02 09:06:53 +03:00
|
|
|
// simulate write operation for struct property which is name is this case
|
|
|
|
func (p *Person) updateName2() {
|
2018-02-01 07:44:47 +03:00
|
|
|
for {
|
2018-02-02 09:06:53 +03:00
|
|
|
p.Name = "Dummy Name 2"
|
2018-02-01 07:44:47 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-02 09:06:53 +03:00
|
|
|
func (p *Person) printName() {
|
2018-02-01 07:44:47 +03:00
|
|
|
for {
|
2018-02-02 09:06:53 +03:00
|
|
|
fmt.Println("Current Name Is : ", p.Name)
|
2018-02-01 07:44:47 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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()
|
2018-02-01 07:44:47 +03:00
|
|
|
// 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
|
|
|
|
}
|