Go cond 锁定期唤醒锁


package main

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

var locker = new(sync.Mutex)
var cond = sync.NewCond(locker)

func test(x int) {
    // 获取锁
    cond.L.Lock()
    // 等待通知  暂时阻塞
    cond.Wait()
    fmt.Println(x)
    time.Sleep(time.Second * 1)
    // 释放锁
    cond.L.Unlock()
}
func main() {
    for i := 0; i < 40; i++ {
        go test(i)
    }
    fmt.Println("start all")
    time.Sleep(time.Second * 3)
    fmt.Println("broadcast")
    // 下发一个通知给已经获取锁的goroutine
    cond.Signal()
    time.Sleep(time.Second * 3)
    // 3秒之后 下发一个通知给已经获取锁的goroutine
    cond.Signal()
    time.Sleep(time.Second * 3)
    // 3秒之后 下发广播给所有等待的goroutine
    cond.Broadcast()
    time.Sleep(time.Second * 60)
}
阅读全文

Go 单例模式


Lazy Loading:

type singleton struct {
}

// private
var instance *singleton

// public
func GetInstance() *singleton {
    if instance == nil {
        // not thread safe
        instance = &singleton{}
    }
    return instance
}

带锁:

type singleton struct {
}

var instance *singleton
var mu sync.Mutex

func GetInstance() *singleton {
    mu.Lock()
    defer mu.Unlock()
    if instance == nil {
        // unnecessary locking if instance already created
        instance = &singleton{}
    }
    return instance
}

带检查锁:

// <-- Not yet perfect. since it's not fully atomic
if instance == nil {
    mu.Lock()
    defer mu.Unlock()
    if instance == nil {
        instance = &singleton{}
    }
}
return instance

阅读全文

Go 打印函数执行时间


package main

import (
    "fmt"
    "time"
)

func timeCost(start time.Time) {
    terminal := time.Since(start)
    fmt.Println(terminal)
}

func main() {
    defer timeCost(time.Now())
    fmt.Println("start program")
    time.Sleep(5 * time.Second)
    fmt.Println("finish program")
}
阅读全文

Go 中如何阻塞等待所有 goroutines 都完成


方案一:

package main

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

// 定义一个同步等待的组
var wg sync.WaitGroup

// 定义一个Printer函数用于并发
func Printer(a int) {
    time.Sleep(2000 * time.Millisecond)
    fmt.Printf("i am %d\n", a)
    defer wg.Done()
}

func main() {
    // 获取cpu个数
    maxProcs := runtime.NumCPU()
    // 限制同时运行的goroutines数量
    runtime.GOMAXPROCS(maxProcs)
    for i := 0; i < 10; i++ {
        //为同步等待组增加一个成员
        wg.Add(1)
        //并发一个goroutine
        go Printer(i)
    }
    // 阻塞等待所有组内成员都执行完毕退栈
    wg.Wait()
    fmt.Println("WE DONE!!!")
}

阅读全文