github.com/tursom/GoCollections@v0.3.10/lang/ThreadLocal.go (about) 1 /* 2 * Copyright (c) 2022 tursom. All rights reserved. 3 * Use of this source code is governed by a GPL-3 4 * license that can be found in the LICENSE file. 5 */ 6 7 package lang 8 9 import ( 10 "github.com/timandy/routine" 11 ) 12 13 //goland:noinspection GoUnusedGlobalVariable 14 var ( 15 ThreadLocalGo = routine.Go 16 ThreadLocalGoWait = routine.GoWait 17 ThreadLocalGoWaitResult = routine.GoWaitResult 18 ) 19 20 type ( 21 ThreadLocal[T any] interface { 22 Object 23 Get() T 24 Put(value T) 25 Remove() 26 } 27 28 threadLocalImpl[T any] struct { 29 BaseObject 30 threadLocal routine.ThreadLocal 31 } 32 ) 33 34 func GoId() int64 { 35 return routine.Goid() 36 } 37 38 //goland:noinspection GoUnusedExportedFunction 39 func NewThreadLocal[T any]() ThreadLocal[T] { 40 return &threadLocalImpl[T]{ 41 threadLocal: routine.NewInheritableThreadLocal(), 42 } 43 } 44 45 //goland:noinspection GoUnusedExportedFunction 46 func NewThreadLocalWithInitial[T any](supplier func() T) ThreadLocal[T] { 47 return &threadLocalImpl[T]{ 48 threadLocal: routine.NewThreadLocalWithInitial(func() any { 49 return supplier() 50 }), 51 } 52 } 53 54 //goland:noinspection GoUnusedExportedFunction 55 func NewInheritableThreadLocal[T any]() ThreadLocal[T] { 56 return &threadLocalImpl[T]{ 57 threadLocal: routine.NewInheritableThreadLocal(), 58 } 59 } 60 61 //goland:noinspection GoUnusedExportedFunction 62 func NewInheritableThreadLocalWithInitial[T any](supplier func() T) ThreadLocal[T] { 63 return &threadLocalImpl[T]{ 64 threadLocal: routine.NewInheritableThreadLocalWithInitial(func() any { 65 return supplier() 66 }), 67 } 68 } 69 70 func (t *threadLocalImpl[T]) Get() T { 71 return Cast[T](t.threadLocal.Get()) 72 } 73 74 func (t *threadLocalImpl[T]) Put(value T) { 75 t.threadLocal.Set(value) 76 } 77 78 func (t *threadLocalImpl[T]) Remove() { 79 t.threadLocal.Remove() 80 }