前言
哈喽,大家好,我是
asong
。最近一个群里看到一个有趣的八股文,问题是:使用context
携带的value
是线程安全的吗?这道题其实就是考察面试者对context
实现原理的理解,如果不知道context
的实现原理,很容易答错这道题,所以本文我们就借着这道题,再重新理解一遍context
携带value
的实现原理。
context
携带value
是线程安全的吗?
先说答案,context
本身就是线程安全的,所以context
携带value
也是线程安全的,写个简单例子验证一下:
func main() {
ctx := context.WithValue(context.Background(), "asong", "test01")
go func() {
for {
_ = context.WithValue(ctx, "asong", "test02")
}
}()
go func() {
for {
_ = context.WithValue(ctx, "asong", "test03")
}
}()
go func() {
for {
fmt.Println(ctx.Value("asong"))