对golang
稍微熟悉的兄弟姐妹们就不用看了!
在看Docker
源码时,碰到了这个语句:
1 container.Lock()
看到上面直接对struct Container
进行上锁时,我翻了一下这个结构体,发现没有定义任何锁啊,怎么上锁的咧。于是我就翻了一下这个结构
体的一些子属性,发现了State
的定义
1 // container/container.go 2 type Container struct { 3 StreamConfig *stream.Config 4 // embed for Container to support states directly. 5 *State `json:"State"` // Needed for Engine API version <= 1.11 6 Root string `json:"-"` // Path to the "home" of the container, including metadata. 7 BaseFS containerfs.ContainerFS `json:"-"` // interface containing graphdriver mount 8 RWLayer layer.RWLayer `json:"-"` 9 .... 10 } 11 12 // container/state.go 13 type State struct { 14 sync.Mutex 15 // Note that `Running` and `Paused` are not mutually exclusive: 16 // When pausing a container (on Linux), the cgroups freezer is used to suspend 17 // all processes in the container. Freezing the process requires the process to 18 // be running. As a result, paused containers are both `Running` _and_ `Paused`. 19 Running bool 20 Paused bool 21 Restarting bool 22 OOMKilled bool 23 RemovalInProgress bool // Not need for this to be persistent on disk. 24 Dead bool 25 Pid int 26 ExitCodeValue int `json:"ExitCode"` 27 ErrorMsg string `json:"Error"` // contains last known error during container start, stop, or remove 28 StartedAt time.Time 29 FinishedAt time.Time 30 Health *Health 31 32 waitStop chan struct{} 33 waitRemove chan struct{} 34 }
当时看到这我就纳闷了(go没学过,没写过,完全新手),咋就直接访问到State
里面的内容了。
看到没,Container
结构体里面定义了*State
之后,就可以直接访问State
里面的成员,这有点类似继承啥玩意的。接下来我们就做个测试,可以瞅瞅。
1 package main 2 3 import ( 4 "fmt" 5 "sync" 6 ) 7 8 type State struct { 9 sync.Mutex 10 Running bool 11 Paused bool 12 } 13 14 type Container struct { 15 *State 16 ID string 17 } 18 19 func NewState() *State { 20 return &State{ 21 Running: false, 22 Paused: false, 23 } 24 } 25 26 func (c *Container) getInfo() error { 27 c.Lock() 28 defer c.Unlock() // defer 可以另写一篇文章说一下 29 fmt.Println("container is locked") 30 return nil 31 } 32 33 func main() { 34 c := Container{State: NewState()} 35 c.getInfo()
36 37 c.Lock() 38 fmt.Println("second lock") 39 c.Unlock() 40 }
运行上面的程序,就可以看到Container
可以直接访问到State
里面的锁。
参考:兔子不吃草
大家可以关注我的微博:阿里云科技快讯
近期有很多抽奖活动,送阿里云纪念品
有疑问加站长微信联系(非本文作者)