官术网_书友最值得收藏!

The simple mutex

In Go, a simple lock is a pointer to a mutex struct type, which belongs to the sync package. We can create a mutex as follows:

var myMutex = &sync.Mutex{}

Let's assume that we have a map called myMap of the map[int]int type that we'd like to protect from the concurrent access of multiple goroutines:

myMutex.Lock()
myMap[1] = 100
myMutex.Unlock()

If we ensure that all goroutines that need to edit myMap have access to myMutex, we can protect myMap against multiple goroutines changing it at the same time.

主站蜘蛛池模板: 庆阳市| 清丰县| 渝北区| 汝州市| 惠东县| 成都市| 芦溪县| 白城市| 靖江市| 东海县| 开封县| 德庆县| 普陀区| 景德镇市| 大悟县| 桐乡市| 澎湖县| 黄陵县| 镇坪县| 许昌市| 丁青县| 乌拉特前旗| 于都县| 乳山市| 屏东县| 镇江市| 唐河县| 格尔木市| 绥宁县| 白银市| 静安区| 通城县| 蓬溪县| 镇远县| 句容市| 铜陵市| 上犹县| 盐源县| 高碑店市| 丹江口市| 阳西县|