码迷,mamicode.com
首页 > 其他好文 > 详细

golang sync.Mutex(2)

时间:2015-04-08 14:39:27      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

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/

golang sync.Mutex(2)

标签:

原文地址:http://www.cnblogs.com/rojas/p/4402257.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!