GoLang Channel与mutex的选择,性能差不多

前端之家收集整理的这篇文章主要介绍了GoLang Channel与mutex的选择,性能差不多前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

go官方应该是更推荐使用chan
https://github.com/golang/go/wiki/MutexOrChannel

以下代码用于测试性能 — 不确保思路是正确的。

package main

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

type Op struct {
    key int
    val int
}

var lock sync.Mutex

var m1 map[int]int
var m2 map[int]int
var max int = 50000

func update_map_by_mutex(i int) {
    lock.Lock()
    m1[i] = i
    if len(m1) == max {
        fmt.Printf("%s mutex finish\n",time.Now())
    }
    lock.Unlock()
}

var ch chan Op

func update_map_by_chan(i int) {
    ch <- Op{key: i,val: i}
}

func wait_for_chan(m map[int]int) {
    for {
        select {
        case op := <-ch:
            m[op.key] = op.val
            if len(m2) == max {
                fmt.Printf("%s chan finish\n",time.Now())
                return
            }
        }
    }
}

func main() {

    m1 = make(map[int]int,max)
    m2 = make(map[int]int,max)
    ch = make(chan Op)
    go wait_for_chan(m2)
    for i := 0; i < max; i++ {
        go update_map_by_chan(i)
        go update_map_by_mutex(i)
    }

    time.Sleep(time.Second * 1)
}

输出结果:

2015-11-17 17:08:18.06992 +0800 CST mutex finish
2015-11-17 17:08:18.0709215 +0800 CST chan finish

mutex性能略好,但chan更go化,更推荐。

原文链接:https://www.f2er.com/go/190092.html

猜你在找的Go相关文章