github.com/timandy/routine@v1.1.4-0.20240507073150-e4a3e1fe2ba5/routine.go (about) 1 package routine 2 3 import "fmt" 4 5 type inheritedTask struct { 6 context *threadLocalMap 7 function Runnable 8 } 9 10 func (it inheritedTask) run(task FutureTask[any]) any { 11 // catch 12 defer func() { 13 if cause := recover(); cause != nil { 14 task.Fail(cause) 15 if err := task.(*futureTask[any]).error; err != nil { 16 fmt.Println(err.Error()) 17 } 18 } 19 }() 20 // restore 21 t := currentThread(it.context != nil) 22 if t == nil { 23 //copied is nil 24 defer func() { 25 t = currentThread(false) 26 if t != nil { 27 t.threadLocals = nil 28 t.inheritableThreadLocals = nil 29 } 30 }() 31 it.function() 32 return nil 33 } else { 34 threadLocalsBackup := t.threadLocals 35 inheritableThreadLocalsBackup := t.inheritableThreadLocals 36 defer func() { 37 t.threadLocals = threadLocalsBackup 38 t.inheritableThreadLocals = inheritableThreadLocalsBackup 39 }() 40 t.threadLocals = nil 41 t.inheritableThreadLocals = it.context 42 it.function() 43 return nil 44 } 45 } 46 47 type inheritedWaitTask struct { 48 context *threadLocalMap 49 function CancelRunnable 50 } 51 52 func (iwt inheritedWaitTask) run(task FutureTask[any]) any { 53 // catch 54 defer func() { 55 if cause := recover(); cause != nil { 56 task.Fail(cause) 57 } 58 }() 59 // restore 60 t := currentThread(iwt.context != nil) 61 if t == nil { 62 //copied is nil 63 defer func() { 64 t = currentThread(false) 65 if t != nil { 66 t.threadLocals = nil 67 t.inheritableThreadLocals = nil 68 } 69 }() 70 iwt.function(task) 71 return nil 72 } else { 73 threadLocalsBackup := t.threadLocals 74 inheritableThreadLocalsBackup := t.inheritableThreadLocals 75 defer func() { 76 t.threadLocals = threadLocalsBackup 77 t.inheritableThreadLocals = inheritableThreadLocalsBackup 78 }() 79 t.threadLocals = nil 80 t.inheritableThreadLocals = iwt.context 81 iwt.function(task) 82 return nil 83 } 84 } 85 86 type inheritedWaitResultTask[TResult any] struct { 87 context *threadLocalMap 88 function CancelCallable[TResult] 89 } 90 91 func (iwrt inheritedWaitResultTask[TResult]) run(task FutureTask[TResult]) TResult { 92 // catch 93 defer func() { 94 if cause := recover(); cause != nil { 95 task.Fail(cause) 96 } 97 }() 98 // restore 99 t := currentThread(iwrt.context != nil) 100 if t == nil { 101 //copied is nil 102 defer func() { 103 t = currentThread(false) 104 if t != nil { 105 t.threadLocals = nil 106 t.inheritableThreadLocals = nil 107 } 108 }() 109 return iwrt.function(task) 110 } else { 111 threadLocalsBackup := t.threadLocals 112 inheritableThreadLocalsBackup := t.inheritableThreadLocals 113 defer func() { 114 t.threadLocals = threadLocalsBackup 115 t.inheritableThreadLocals = inheritableThreadLocalsBackup 116 }() 117 t.threadLocals = nil 118 t.inheritableThreadLocals = iwrt.context 119 return iwrt.function(task) 120 } 121 }