golang sync.Mutex(2)

复制代码
package main

import (
    "fmt"
    "sync"
    "time"
)

type User struct {
    Name   string
    Locker *sync.Mutex
}

func (u *User) SetName(wati *sync.WaitGroup, name string) {
    defer func() {
        fmt.Println("Unlock set name:", name)
        u.Locker.Unlock()
        wati.Done()
    }()

    u.Locker.Lock()
    fmt.Println("Lock set name:", name)
    time.Sleep(1 * time.Second)
    u.Name = name
}

func (u *User) GetName(wati *sync.WaitGroup) {
    defer func() {
        fmt.Println("Unlock get name:", u.Name)
        u.Locker.Unlock()
        wati.Done()
    }()

    u.Locker.Lock()
    fmt.Println("Lock get name:", u.Name)
    time.Sleep(1 * time.Second)
}

func main() {
    user := User{}
    user.Locker = new(sync.Mutex)
    wait := &sync.WaitGroup{}
    names := []string{"a", "b", "c"}
    for _, name := range names {
        wait.Add(2)
        go user.SetName(wait, name)
        go user.GetName(wait)
    }

    wait.Wait()
}
复制代码

转自:http://www.liguosong.com/2014/05/07/golang-sync-mutex/

posted on   rojas  阅读(395)  评论(0)    收藏  举报

< 2025年4月 >
30 31 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 1 2 3
4 5 6 7 8 9 10

统计

点击右上角即可分享
微信分享提示