协程与map

今天遇到一个性能问题,细查发现是几个并发协程里面都用到了一个全局的map变量。由于map并不是并发安全的,所以不得不在每个协程里面加写锁,虽然锁的粒度是较小的读写锁,但加锁的本质就是让并发变成了同步。 

所以我们在协程里面应该避免使用全局的map变量。但又想保存协程的返回值怎么办?

办法1: 使用通道

package main

import (
	"time"
	"fmt"
)

func main() {
	intChan := make(chan int)
	var getres int

	go func(ch chan int){
		ch <- 666
	}(intChan)

	getres = <-intChan
	time.Sleep(1 * time.Second)
	fmt.Println(getres)
}

办法2: 用变量的地址

package main

import (
	"time"
	"fmt"
)

func main() {
	str := ""
	go func(str* string){
		*str = "nbn"
	}(&str)

	time.Sleep(1 * time.Second)
	fmt.Println(str)
}


猜你喜欢

转载自my.oschina.net/u/3707537/blog/1813384