[Golang]golang中自动锁的实现

golang作为原生支持多线程的语言,为了实现线程安全的package,经常需要对全局变量自动加锁,以便安全的访问全局变量。
废话不多说,直接上代码:
package main
import (
       "sync"
    "fmt"
)

type AutoLock struct {
    obj  interface{}
    lock sync.Mutex
}

func (me *AutoLock) SafeSet(obj interface{}) {
    me.lock.Lock()
    defer me.lock.Unlock()
    me.obj = obj
}

func (me *AutoLock) LockGet() interface{} {
    me.lock.Lock()
    return me.obj
}

func (me *AutoLock) Unlock() {
    me.lock.Unlock()
}
 
 
 
 
var g_val AutoLock
func gorutine_func(ch chan int) {
    r := g_val.LockGet().(*int)
    defer g_val.Unlock()
    *r++
    fmt.Println(*r)
    ch <- 1
}
func main() {
    g_val.SafeSet(new(int))
    const n = 10
    ch := make(chan int)
    for i := 0; i < n; i++ {
        go gorutine_func(ch)
    }
    for i := 0; i  i++ {
        <-ch
    }
}
posted @ 2014-11-09 19:56  AllyDale  阅读(35)  评论(0)    收藏  举报