Gopl 第九章 共享变量

说明

本文为GOPL第九章学习笔记

互斥锁

互斥锁是计数上限为1的信号量

互斥锁: sync.Mutex的基本使用

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
package main

import (
"fmt"
"sync"
)
var(
balance int
mu sync.Mutex
)
func Deposit(amount int){
mu.Lock()
balance = balance + amount
mu.Unlock()
}
func Balance() int {
mu.Lock()
b := balance
mu.Unlock()
return b
}

func main(){
var n sync.WaitGroup
for i := 1; i<= 1000; i++ {
n.Add(1)
go func(amount int){
Deposit(amount)
n.Done()
}(i)
}
n.Wait()
if got, want := Balance(), (1000+1)*1000/2; got != want {
fmt.Printf("Balance = %d, want %d\n", got, want)
}
fmt.Println(Balance())
}

取款超额问题

错误做法

进行超额取款的某一瞬间,有可能导致小额取款失败

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
package main

import (
"fmt"
"sync"
)
var(
balance int
mu sync.Mutex
)
func Deposit(amount int){
mu.Lock()
balance = balance + amount
mu.Unlock()
}
func Balance() int {
mu.Lock()
b := balance
mu.Unlock()
return b
}

func Withdraw(amount int) bool{
Deposit(-amount)
if Balance()<0 {
Deposit(amount)
return false //余额不足,退出取款
}
return true
}

func main(){
Deposit(50000)
var n2 sync.WaitGroup
for i :=1; i<1000; i++{
n2.Add(1)
go func(){
Withdraw(1000000)
n2.Done()
}()
}
for i :=1; i<1000; i++{
n2.Add(1)
go func(){
ok := Withdraw(1)
if !ok{
fmt.Println("取款1元失败")
//存在某个瞬间余额小于0,会导致小额取款失败
}else {
fmt.Println("取款一元成功")
}
n2.Done()
}()
}
n2.Wait()

}

一种解决方案

尝试在Withdraw函数加锁,为此需要取消调用Deposit()函数

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
package main

import (
"fmt"
"sync"
)
var(
balance int
mu sync.Mutex
)
func Deposit(amount int){
mu.Lock()
balance = balance + amount
mu.Unlock()
}
func Balance() int {
mu.Lock()
b := balance
mu.Unlock()
return b
}

func Withdraw1(amount int) bool{
mu.Lock()
defer mu.Unlock()
balance -= amount
if balance <0 {
balance += amount
return false //余额不足,退出取款
}
return true
}
func main(){
Deposit(50000)
var n2 sync.WaitGroup
for i :=1; i<1000; i++{
n2.Add(1)
go func(){
Withdraw1(1000000)
n2.Done()
}()
}
for i :=1; i<1000; i++{
n2.Add(1)
go func(){
ok := Withdraw1(1)
if !ok{
fmt.Println("取款1元失败")
}else {
fmt.Println("取款一元成功")
}
n2.Done()
}()
}
n2.Wait()

}

读写互斥锁: sync.RWMutex

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
package main

import (
"fmt"
"sync"
)
var(
balance int
mu sync.RWMutex
)
func Deposit(amount int){
mu.Lock()
balance = balance + amount
mu.Unlock()
}
func Balance() int {
mu.RLock()
defer mu.RUnlock()
return balance
}
func main(){
var n sync.WaitGroup
Deposit(1000)
for i := 1;i<10000 ;i++{
n.Add(1)
go func() {
fmt.Printf("%d\n", Balance())
n.Done()
}()
n.Add(1)
go func() {
Deposit(i*1234)
n.Done()
}()
}
n.Wait()
}

并发非阻塞函数缓存

并发阻塞版本

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
package main

import (
"fmt"
"io/ioutil"
"log"
"net/http"
"sync"
"time"
)

//函数缓存
type Memo struct {
f Func
cache map[string]result
mu sync.Mutex
}

type Func func(key string) (interface{},error)

type result struct {
value interface{}
err error
}

func (memo *Memo) Get(key string) (interface{}, error){
memo.mu.Lock()
res, ok := memo.cache[key]
memo.mu.Unlock()
if !ok{
res.value, res.err = memo.f(key)
memo.mu.Lock()
memo.cache[key] = res
memo.mu.Unlock()
}

return res.value, res.err
}

func New(f Func) *Memo{
return &Memo{f: f, cache:make(map[string]result)}
}

func httpGetBody(url string) (interface{},error){
resp, err := http.Get(url)
if err!= nil{
return nil , err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
func main(){
m := New(httpGetBody)
urls := []string{"http://baidu.com",
"http://hao123.com",
"http://360.com",
"http://baidu.com",
"http://hao123.com",
"http://360.com"}
var n sync.WaitGroup
for _, url := range urls{
n.Add(1)
go func(url string) {
start := time.Now()
value, err := m.Get(url)
if err != nil {
log.Print(err)
}
fmt.Printf("%s, %s, %d bytes\n", url, time.Since(start), len(value.([]byte)))
n.Done()
}(url)
}
n.Wait()
}
//
http://baidu.com, 195.4771ms, 81 bytes
http://baidu.com, 195.4771ms, 81 bytes
http://360.com, 330.128ms, 75192 bytes
http://360.com, 331.1178ms, 75192 bytes
http://hao123.com, 391.9548ms, 291344 bytes
http://hao123.com, 559.5049ms, 291344 bytes
//

并发非阻塞版本

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
87
88
89
90
package main

import (
"fmt"
"io/ioutil"
"log"
"net/http"
"sync"
"time"
)

//函数缓存
type Memo struct {
f Func
cache map[string]*entry
mu sync.Mutex
}

type Func func(key string) (interface{},error)

type result struct {
value interface{}
err error
}
type entry struct{
res result
ready chan struct{}
}

func (memo *Memo) Get(key string) (interface{}, error){
memo.mu.Lock()
en := memo.cache[key]
if en == nil{
en = &entry{ready:make(chan struct{})}
memo.cache[key] = en
memo.mu.Unlock()

en.res.value, en.res.err = memo.f(key)
close(en.ready)
}else {
memo.mu.Unlock()
<- en.ready
}

return en.res.value, en.res.err
}

func New(f Func) *Memo{
return &Memo{f: f, cache:make(map[string]*entry)}
}

func httpGetBody(url string) (interface{},error){
resp, err := http.Get(url)
if err!= nil{
return nil , err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
func main(){
m := New(httpGetBody)
urls := []string{"http://baidu.com",
"http://hao123.com",
"http://360.com",
"http://baidu.com",
"http://hao123.com",
"http://360.com"}
var n sync.WaitGroup
for _, url := range urls{
n.Add(1)
go func(url string) {
start := time.Now()
value, err := m.Get(url)
if err != nil {
log.Print(err)
}
fmt.Printf("%s, %s, %d bytes\n", url, time.Since(start), len(value.([]byte)))
n.Done()
}(url)
}
n.Wait()
}
//
http://baidu.com, 193.4525ms, 81 bytes
http://baidu.com, 193.4525ms, 81 bytes
http://360.com, 303.1589ms, 75192 bytes
http://360.com, 303.1589ms, 75192 bytes
http://hao123.com, 411.8675ms, 291366 bytes
http://hao123.com, 411.8675ms, 291366 bytes
//