• 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/

  • 相关阅读:
    Python
    Python
    Python
    Python
    Python
    Python
    Python
    python
    对象
    py常用模块
  • 原文地址:https://www.cnblogs.com/rojas/p/4402257.html
Copyright © 2020-2023  润新知