cubefs
205 строк · 5.2 Кб
1// Copyright 2013 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
5// Package singleflight provides a duplicate function call suppression
6// mechanism.
7package singleflight // import "golang.org/x/sync/singleflight"
8
9import (
10"bytes"
11"errors"
12"fmt"
13"runtime"
14"runtime/debug"
15"sync"
16)
17
18// errGoexit indicates the runtime.Goexit was called in
19// the user given function.
20var errGoexit = errors.New("runtime.Goexit was called")
21
22// A panicError is an arbitrary value recovered from a panic
23// with the stack trace during the execution of given function.
24type panicError struct {
25value interface{}
26stack []byte
27}
28
29// Error implements error interface.
30func (p *panicError) Error() string {
31return fmt.Sprintf("%v\n\n%s", p.value, p.stack)
32}
33
34func newPanicError(v interface{}) error {
35stack := debug.Stack()
36
37// The first line of the stack trace is of the form "goroutine N [status]:"
38// but by the time the panic reaches Do the goroutine may no longer exist
39// and its status will have changed. Trim out the misleading line.
40if line := bytes.IndexByte(stack[:], '\n'); line >= 0 {
41stack = stack[line+1:]
42}
43return &panicError{value: v, stack: stack}
44}
45
46// call is an in-flight or completed singleflight.Do call
47type call struct {
48wg sync.WaitGroup
49
50// These fields are written once before the WaitGroup is done
51// and are only read after the WaitGroup is done.
52val interface{}
53err error
54
55// These fields are read and written with the singleflight
56// mutex held before the WaitGroup is done, and are read but
57// not written after the WaitGroup is done.
58dups int
59chans []chan<- Result
60}
61
62// Group represents a class of work and forms a namespace in
63// which units of work can be executed with duplicate suppression.
64type Group struct {
65mu sync.Mutex // protects m
66m map[string]*call // lazily initialized
67}
68
69// Result holds the results of Do, so they can be passed
70// on a channel.
71type Result struct {
72Val interface{}
73Err error
74Shared bool
75}
76
77// Do executes and returns the results of the given function, making
78// sure that only one execution is in-flight for a given key at a
79// time. If a duplicate comes in, the duplicate caller waits for the
80// original to complete and receives the same results.
81// The return value shared indicates whether v was given to multiple callers.
82func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) {
83g.mu.Lock()
84if g.m == nil {
85g.m = make(map[string]*call)
86}
87if c, ok := g.m[key]; ok {
88c.dups++
89g.mu.Unlock()
90c.wg.Wait()
91
92if e, ok := c.err.(*panicError); ok {
93panic(e)
94} else if c.err == errGoexit {
95runtime.Goexit()
96}
97return c.val, c.err, true
98}
99c := new(call)
100c.wg.Add(1)
101g.m[key] = c
102g.mu.Unlock()
103
104g.doCall(c, key, fn)
105return c.val, c.err, c.dups > 0
106}
107
108// DoChan is like Do but returns a channel that will receive the
109// results when they are ready.
110//
111// The returned channel will not be closed.
112func (g *Group) DoChan(key string, fn func() (interface{}, error)) <-chan Result {
113ch := make(chan Result, 1)
114g.mu.Lock()
115if g.m == nil {
116g.m = make(map[string]*call)
117}
118if c, ok := g.m[key]; ok {
119c.dups++
120c.chans = append(c.chans, ch)
121g.mu.Unlock()
122return ch
123}
124c := &call{chans: []chan<- Result{ch}}
125c.wg.Add(1)
126g.m[key] = c
127g.mu.Unlock()
128
129go g.doCall(c, key, fn)
130
131return ch
132}
133
134// doCall handles the single call for a key.
135func (g *Group) doCall(c *call, key string, fn func() (interface{}, error)) {
136normalReturn := false
137recovered := false
138
139// use double-defer to distinguish panic from runtime.Goexit,
140// more details see https://golang.org/cl/134395
141defer func() {
142// the given function invoked runtime.Goexit
143if !normalReturn && !recovered {
144c.err = errGoexit
145}
146
147g.mu.Lock()
148defer g.mu.Unlock()
149c.wg.Done()
150if g.m[key] == c {
151delete(g.m, key)
152}
153
154if e, ok := c.err.(*panicError); ok {
155// In order to prevent the waiting channels from being blocked forever,
156// needs to ensure that this panic cannot be recovered.
157if len(c.chans) > 0 {
158go panic(e)
159select {} // Keep this goroutine around so that it will appear in the crash dump.
160} else {
161panic(e)
162}
163} else if c.err == errGoexit {
164// Already in the process of goexit, no need to call again
165} else {
166// Normal return
167for _, ch := range c.chans {
168ch <- Result{c.val, c.err, c.dups > 0}
169}
170}
171}()
172
173func() {
174defer func() {
175if !normalReturn {
176// Ideally, we would wait to take a stack trace until we've determined
177// whether this is a panic or a runtime.Goexit.
178//
179// Unfortunately, the only way we can distinguish the two is to see
180// whether the recover stopped the goroutine from terminating, and by
181// the time we know that, the part of the stack trace relevant to the
182// panic has been discarded.
183if r := recover(); r != nil {
184c.err = newPanicError(r)
185}
186}
187}()
188
189c.val, c.err = fn()
190normalReturn = true
191}()
192
193if !normalReturn {
194recovered = true
195}
196}
197
198// Forget tells the singleflight to forget about a key. Future calls
199// to Do for this key will call the function rather than waiting for
200// an earlier call to complete.
201func (g *Group) Forget(key string) {
202g.mu.Lock()
203delete(g.m, key)
204g.mu.Unlock()
205}
206