本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

301 lines
7.9KB

  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build !go1.7
  5. package context
  6. import (
  7. "errors"
  8. "fmt"
  9. "sync"
  10. "time"
  11. )
  12. // An emptyCtx is never canceled, has no values, and has no deadline. It is not
  13. // struct{}, since vars of this type must have distinct addresses.
  14. type emptyCtx int
  15. func (*emptyCtx) Deadline() (deadline time.Time, ok bool) {
  16. return
  17. }
  18. func (*emptyCtx) Done() <-chan struct{} {
  19. return nil
  20. }
  21. func (*emptyCtx) Err() error {
  22. return nil
  23. }
  24. func (*emptyCtx) Value(key interface{}) interface{} {
  25. return nil
  26. }
  27. func (e *emptyCtx) String() string {
  28. switch e {
  29. case background:
  30. return "context.Background"
  31. case todo:
  32. return "context.TODO"
  33. }
  34. return "unknown empty Context"
  35. }
  36. var (
  37. background = new(emptyCtx)
  38. todo = new(emptyCtx)
  39. )
  40. // Canceled is the error returned by Context.Err when the context is canceled.
  41. var Canceled = errors.New("context canceled")
  42. // DeadlineExceeded is the error returned by Context.Err when the context's
  43. // deadline passes.
  44. var DeadlineExceeded = errors.New("context deadline exceeded")
  45. // WithCancel returns a copy of parent with a new Done channel. The returned
  46. // context's Done channel is closed when the returned cancel function is called
  47. // or when the parent context's Done channel is closed, whichever happens first.
  48. //
  49. // Canceling this context releases resources associated with it, so code should
  50. // call cancel as soon as the operations running in this Context complete.
  51. func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
  52. c := newCancelCtx(parent)
  53. propagateCancel(parent, c)
  54. return c, func() { c.cancel(true, Canceled) }
  55. }
  56. // newCancelCtx returns an initialized cancelCtx.
  57. func newCancelCtx(parent Context) *cancelCtx {
  58. return &cancelCtx{
  59. Context: parent,
  60. done: make(chan struct{}),
  61. }
  62. }
  63. // propagateCancel arranges for child to be canceled when parent is.
  64. func propagateCancel(parent Context, child canceler) {
  65. if parent.Done() == nil {
  66. return // parent is never canceled
  67. }
  68. if p, ok := parentCancelCtx(parent); ok {
  69. p.mu.Lock()
  70. if p.err != nil {
  71. // parent has already been canceled
  72. child.cancel(false, p.err)
  73. } else {
  74. if p.children == nil {
  75. p.children = make(map[canceler]bool)
  76. }
  77. p.children[child] = true
  78. }
  79. p.mu.Unlock()
  80. } else {
  81. go func() {
  82. select {
  83. case <-parent.Done():
  84. child.cancel(false, parent.Err())
  85. case <-child.Done():
  86. }
  87. }()
  88. }
  89. }
  90. // parentCancelCtx follows a chain of parent references until it finds a
  91. // *cancelCtx. This function understands how each of the concrete types in this
  92. // package represents its parent.
  93. func parentCancelCtx(parent Context) (*cancelCtx, bool) {
  94. for {
  95. switch c := parent.(type) {
  96. case *cancelCtx:
  97. return c, true
  98. case *timerCtx:
  99. return c.cancelCtx, true
  100. case *valueCtx:
  101. parent = c.Context
  102. default:
  103. return nil, false
  104. }
  105. }
  106. }
  107. // removeChild removes a context from its parent.
  108. func removeChild(parent Context, child canceler) {
  109. p, ok := parentCancelCtx(parent)
  110. if !ok {
  111. return
  112. }
  113. p.mu.Lock()
  114. if p.children != nil {
  115. delete(p.children, child)
  116. }
  117. p.mu.Unlock()
  118. }
  119. // A canceler is a context type that can be canceled directly. The
  120. // implementations are *cancelCtx and *timerCtx.
  121. type canceler interface {
  122. cancel(removeFromParent bool, err error)
  123. Done() <-chan struct{}
  124. }
  125. // A cancelCtx can be canceled. When canceled, it also cancels any children
  126. // that implement canceler.
  127. type cancelCtx struct {
  128. Context
  129. done chan struct{} // closed by the first cancel call.
  130. mu sync.Mutex
  131. children map[canceler]bool // set to nil by the first cancel call
  132. err error // set to non-nil by the first cancel call
  133. }
  134. func (c *cancelCtx) Done() <-chan struct{} {
  135. return c.done
  136. }
  137. func (c *cancelCtx) Err() error {
  138. c.mu.Lock()
  139. defer c.mu.Unlock()
  140. return c.err
  141. }
  142. func (c *cancelCtx) String() string {
  143. return fmt.Sprintf("%v.WithCancel", c.Context)
  144. }
  145. // cancel closes c.done, cancels each of c's children, and, if
  146. // removeFromParent is true, removes c from its parent's children.
  147. func (c *cancelCtx) cancel(removeFromParent bool, err error) {
  148. if err == nil {
  149. panic("context: internal error: missing cancel error")
  150. }
  151. c.mu.Lock()
  152. if c.err != nil {
  153. c.mu.Unlock()
  154. return // already canceled
  155. }
  156. c.err = err
  157. close(c.done)
  158. for child := range c.children {
  159. // NOTE: acquiring the child's lock while holding parent's lock.
  160. child.cancel(false, err)
  161. }
  162. c.children = nil
  163. c.mu.Unlock()
  164. if removeFromParent {
  165. removeChild(c.Context, c)
  166. }
  167. }
  168. // WithDeadline returns a copy of the parent context with the deadline adjusted
  169. // to be no later than d. If the parent's deadline is already earlier than d,
  170. // WithDeadline(parent, d) is semantically equivalent to parent. The returned
  171. // context's Done channel is closed when the deadline expires, when the returned
  172. // cancel function is called, or when the parent context's Done channel is
  173. // closed, whichever happens first.
  174. //
  175. // Canceling this context releases resources associated with it, so code should
  176. // call cancel as soon as the operations running in this Context complete.
  177. func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {
  178. if cur, ok := parent.Deadline(); ok && cur.Before(deadline) {
  179. // The current deadline is already sooner than the new one.
  180. return WithCancel(parent)
  181. }
  182. c := &timerCtx{
  183. cancelCtx: newCancelCtx(parent),
  184. deadline: deadline,
  185. }
  186. propagateCancel(parent, c)
  187. d := deadline.Sub(time.Now())
  188. if d <= 0 {
  189. c.cancel(true, DeadlineExceeded) // deadline has already passed
  190. return c, func() { c.cancel(true, Canceled) }
  191. }
  192. c.mu.Lock()
  193. defer c.mu.Unlock()
  194. if c.err == nil {
  195. c.timer = time.AfterFunc(d, func() {
  196. c.cancel(true, DeadlineExceeded)
  197. })
  198. }
  199. return c, func() { c.cancel(true, Canceled) }
  200. }
  201. // A timerCtx carries a timer and a deadline. It embeds a cancelCtx to
  202. // implement Done and Err. It implements cancel by stopping its timer then
  203. // delegating to cancelCtx.cancel.
  204. type timerCtx struct {
  205. *cancelCtx
  206. timer *time.Timer // Under cancelCtx.mu.
  207. deadline time.Time
  208. }
  209. func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
  210. return c.deadline, true
  211. }
  212. func (c *timerCtx) String() string {
  213. return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now()))
  214. }
  215. func (c *timerCtx) cancel(removeFromParent bool, err error) {
  216. c.cancelCtx.cancel(false, err)
  217. if removeFromParent {
  218. // Remove this timerCtx from its parent cancelCtx's children.
  219. removeChild(c.cancelCtx.Context, c)
  220. }
  221. c.mu.Lock()
  222. if c.timer != nil {
  223. c.timer.Stop()
  224. c.timer = nil
  225. }
  226. c.mu.Unlock()
  227. }
  228. // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
  229. //
  230. // Canceling this context releases resources associated with it, so code should
  231. // call cancel as soon as the operations running in this Context complete:
  232. //
  233. // func slowOperationWithTimeout(ctx context.Context) (Result, error) {
  234. // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
  235. // defer cancel() // releases resources if slowOperation completes before timeout elapses
  236. // return slowOperation(ctx)
  237. // }
  238. func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
  239. return WithDeadline(parent, time.Now().Add(timeout))
  240. }
  241. // WithValue returns a copy of parent in which the value associated with key is
  242. // val.
  243. //
  244. // Use context Values only for request-scoped data that transits processes and
  245. // APIs, not for passing optional parameters to functions.
  246. func WithValue(parent Context, key interface{}, val interface{}) Context {
  247. return &valueCtx{parent, key, val}
  248. }
  249. // A valueCtx carries a key-value pair. It implements Value for that key and
  250. // delegates all other calls to the embedded Context.
  251. type valueCtx struct {
  252. Context
  253. key, val interface{}
  254. }
  255. func (c *valueCtx) String() string {
  256. return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val)
  257. }
  258. func (c *valueCtx) Value(key interface{}) interface{} {
  259. if c.key == key {
  260. return c.val
  261. }
  262. return c.Context.Value(key)
  263. }
上海开阖软件有限公司 沪ICP备12045867号-1