RT ..
import (
"fmt"
"sync"
)
var g_pMutex *sync.Mutex
var g_iCount int32
func Test_Mutex() {
Logger.Debug( "Test_Mutex Beg" )
defer Logger.Debug( "Test_Mutex End" )
fmt.Println( "" )
g_pMutex = new( sync.Mutex )
Logger.Debugf( "g_pMutex=0X%X", &g_pMutex )
g_iCount = 0
pfnFunc := func ( pMutex *sync.Mutex ) {
Logger.Debug( "TestUse Beg" )
defer Logger.Debug( "TestUse End" )
Logger.Debugf( "pMutex=0X%X", &pMutex )
pMutex.Lock()
defer pMutex.Unlock()
g_iCount ++
}
pfnFunc( g_pMutex )
}
结果如下
![333.png](http://studygolang.qiniudn.com/160817/14d7fd63b37462ef06c45112bc8a52cb.png)
为啥 外面的 g_pMutex 和pfnFunc := func ( pMutex *sync.Mutex ) 函数内的pMutex 地址不同。
![333.png](http://studygolang.qiniudn.com/160817/c20def1bc7af5edff6c5ce4ac5635521.png)
#2
更多评论
结果,再发一次
2016-08-17 00:43:40 1471365820260269854 [Debug] t_Mutex.go:23 [Test_Mutex Beg]
2016-08-17 00:43:40 1471365820260280118 [Debug] t_Mutex.go:29 [g_pMutex=0XAEA460]
2016-08-17 00:43:40 1471365820260282767 [Debug] t_Mutex.go:35 [TestUse Beg]
2016-08-17 00:43:40 1471365820260284942 [Debug] t_Mutex.go:38 [pMutex=0XC82002C128]
2016-08-17 00:43:40 1471365820260287015 [Debug] t_Mutex.go:44 [TestUse End]
2016-08-17 00:43:40 1471365820260288973 [Debug] t_Mutex.go:48 [Test_Mutex End]
#1
很正常,闭包和方法是一样的,你传入的参数是复制的,两个指针的地址自然不一样。但两个指针指向的值却是一样的,这是两个不同的概念。你可以在闭包内外,通过"p"格式指令,对比一下:
```code
package main
import (
"fmt"
"sync"
)
var g_pMutex *sync.Mutex
var g_iCount int32
func main() {
fmt.Println( "Test_Mutex Beg" )
defer fmt.Println( "Test_Mutex End" )
fmt.Println( "" )
g_pMutex = new( sync.Mutex )
fmt.Printf( "g_pMutex=%p \n", g_pMutex )
fmt.Printf( "&g_pMutex=%p \n", &g_pMutex )
g_iCount = 0
pfnFunc := func ( pMutex *sync.Mutex ) {
fmt.Println( "TestUse Beg" )
defer fmt.Println( "TestUse End" )
fmt.Printf( "pMutex=%p \n", pMutex )
fmt.Printf( "&pMutex=%p \n", &pMutex )
pMutex.Lock()
defer pMutex.Unlock()
g_iCount ++
}
pfnFunc( g_pMutex )
fmt.Println("g_iCount=",g_iCount)
}
```
#3