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/

本文来自:博客园

感谢作者:rojas

查看原文:golang sync.Mutex(2)

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。