本文整理汇总了Golang中sync.Once类的典型用法代码示例。如果您正苦于以下问题:Golang Once类的具体用法?Golang Once怎么用?Golang Once使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Once类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Open
// Open connects to the existing window with the given id.
// If ctl is non-nil, Open uses it as the window's control file
// and takes ownership of it.
func Open(id int, ctl *client.Fid) (*Win, error) {
config := new(sync.Once)
config.Do(mountAcme)
if fsysErr != nil {
return nil, fsysErr
}
if ctl == nil {
var err error
ctl, err = fsys.Open(fmt.Sprintf("%d/ctl", id), plan9.ORDWR)
if err != nil {
return nil, err
}
}
w := new(Win)
w.id = id
w.ctl = ctl
w.next = nil
w.prev = last
if last != nil {
last.next = w
} else {
windows = w
}
last = w
return w, nil
}
示例2: TestConcurrentSqliteConns
// TestConcurrentSqliteConns tests concurrent writes to a single in memory database.
func TestConcurrentSqliteConns(t *testing.T) {
dbMap := NewMemDB()
repo := NewConnectorConfigRepo(dbMap)
var (
once sync.Once
wg sync.WaitGroup
)
n := 1000
wg.Add(n)
for i := 0; i < n; i++ {
go func() {
configs := []connector.ConnectorConfig{
&connector.LocalConnectorConfig{ID: "local"},
}
// Setting connector configs both deletes and writes to a single table
// within a transaction.
if err := repo.Set(configs); err != nil {
// Don't print 1000 errors, only the first.
once.Do(func() {
t.Errorf("concurrent connections to sqlite3: %v", err)
})
}
wg.Done()
}()
}
wg.Wait()
}
示例3: main
func main() {
Case := Init(2)
fmt.Printf("DEADLOCK\n")
var mu sync.Mutex
var once sync.Once
done := make(chan bool)
go func() {
if Case == 0 {
time.Sleep(time.Second)
}
mu.Lock()
once.Do(func() {
mu.Lock()
mu.Unlock()
})
mu.Unlock()
done <- true
}()
if Case == 1 {
time.Sleep(time.Second)
}
once.Do(func() {
mu.Lock()
mu.Unlock()
})
<-done
}
示例4: Paralyze
// Paralyze parallelizes a function and returns a slice containing results and
// a slice containing errors. The results at each index are not mutually exclusive,
// that is if results[i] is not nil, errors[i] is not guaranteed to be nil.
func Paralyze(funcs ...Paralyzable) (results []interface{}, errors []error) {
var wg sync.WaitGroup
results = make([]interface{}, len(funcs))
errors = make([]error, len(funcs))
wg.Add(len(funcs))
var panik interface{}
var panikOnce sync.Once
for i, fn := range funcs {
go func(i int, fn Paralyzable) {
defer func() {
if r := recover(); r != nil {
panikOnce.Do(func() { panik = r })
}
}()
defer wg.Done()
results[i], errors[i] = fn()
}(i, fn)
}
wg.Wait()
if panik != nil {
panic(panik)
}
return results, errors
}
示例5: make_icom_ctx
func make_icom_ctx(underlying io.ReadWriteCloser, is_server bool,
do_junk bool, PAUSELIM int) *icom_ctx {
ctx := new(icom_ctx)
ctx.is_dead = false
ctx.underlying = underlying
ctx.our_srv = VSListen()
ctx.write_ch = make(chan icom_msg)
// Killswitch is closed when the entire ctx should be abandoned.
killswitch := make(chan bool)
ctx.killswitch = killswitch
var _ks_exec sync.Once
KILL := func() {
_ks_exec.Do(func() {
kilog.Debug("Killswitching!")
ctx.underlying.Close()
ctx.is_dead = true
close(killswitch)
close(ctx.our_srv.vs_ch)
})
}
// Run the main thing
go run_icom_ctx(ctx, KILL, is_server, do_junk, PAUSELIM)
return ctx
}
示例6: waitTillInboundEmpty
// waitTillInboundEmpty will run f which should end up causing the peer with hostPort in ch
// to have 0 inbound connections. It will fail the test after a second.
func waitTillInboundEmpty(t *testing.T, ch *Channel, hostPort string, f func()) {
peer, ok := ch.RootPeers().Get(hostPort)
if !ok {
return
}
inboundEmpty := make(chan struct{})
var onUpdateOnce sync.Once
onUpdate := func(p *Peer) {
if inbound, _ := p.NumConnections(); inbound == 0 {
onUpdateOnce.Do(func() {
close(inboundEmpty)
})
}
}
peer.SetOnUpdate(onUpdate)
f()
select {
case <-inboundEmpty:
return
case <-time.After(time.Second):
t.Errorf("Timed out waiting for peer %v to have no inbound connections", hostPort)
}
}
示例7: checkErr
func checkErr(t *testing.T, err error, once *sync.Once) bool {
if err.(*url.Error).Err == io.EOF {
return true
}
var errno syscall.Errno
switch oe := err.(*url.Error).Err.(type) {
case *net.OpError:
switch e := oe.Err.(type) {
case syscall.Errno:
errno = e
case *os.SyscallError:
errno = e.Err.(syscall.Errno)
}
if errno == syscall.ECONNREFUSED {
return true
} else if err != nil {
once.Do(func() {
t.Error("Error on Get:", err)
})
}
default:
if strings.Contains(err.Error(), "transport closed before response was received") {
return true
}
if strings.Contains(err.Error(), "server closed connection") {
return true
}
fmt.Printf("unknown err: %s, %#v\n", err, err)
}
return false
}
示例8: Pipe
func Pipe(src io.ReadWriteCloser, dst io.ReadWriteCloser) (int64, int64) {
var sent, received int64
var c = make(chan bool)
var o sync.Once
close := func() {
src.Close()
dst.Close()
close(c)
}
go func() {
received, _ = io.Copy(src, dst)
o.Do(close)
}()
go func() {
sent, _ = io.Copy(dst, src)
o.Do(close)
}()
<-c
return received, sent
}
示例9: executeStreamSql
func (qe *QueryEngine) executeStreamSql(logStats *sqlQueryStats, conn PoolConnection, sql string, callback func(interface{}) error) {
waitStart := time.Now()
if !qe.streamTokens.Acquire() {
panic(NewTabletError(FAIL, "timed out waiting for streaming quota"))
}
// Guarantee a release in case of unexpected errors.
var once sync.Once
defer once.Do(qe.streamTokens.Release)
waitTime := time.Now().Sub(waitStart)
waitStats.Add("StreamToken", waitTime)
// No need create a new log variable for this. Just add to the total
// connection wait time.
logStats.WaitingForConnection += waitTime
logStats.QuerySources |= QUERY_SOURCE_MYSQL
logStats.NumberOfQueries += 1
logStats.AddRewrittenSql(sql)
fetchStart := time.Now()
err := conn.ExecuteStreamFetch(
sql,
func(qr interface{}) error {
// Release semaphore at first callback.
once.Do(qe.streamTokens.Release)
return callback(qr)
},
int(qe.streamBufferSize.Get()),
)
logStats.MysqlResponseTime += time.Now().Sub(fetchStart)
if err != nil {
panic(NewTabletErrorSql(FAIL, err))
}
}
示例10: TestHeartbeatCB
func TestHeartbeatCB(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop()
serverClock := hlc.NewClock(time.Unix(0, 20).UnixNano)
serverCtx := newNodeTestContext(serverClock, stopper)
s, ln := newTestServer(t, serverCtx, true)
remoteAddr := ln.Addr().String()
RegisterHeartbeatServer(s, &HeartbeatService{
clock: serverClock,
remoteClockMonitor: serverCtx.RemoteClocks,
})
// Clocks don't matter in this test.
clientCtx := newNodeTestContext(serverClock, stopper)
var once sync.Once
ch := make(chan struct{})
clientCtx.HeartbeatCB = func() {
once.Do(func() {
close(ch)
})
}
_, err := clientCtx.GRPCDial(remoteAddr)
if err != nil {
t.Fatal(err)
}
<-ch
}
示例11: Simulate
func (s *Storage) Simulate(numPath, perSec int) func() {
var terminate = make(chan bool)
for i := 0; i < numPath; i++ {
_path := "/" + randomString()
go func() {
for {
select {
case <-time.After(time.Second / time.Duration(perSec)):
_addr := randomString()
s.Push(_path, _addr)
case <-terminate:
return
}
}
}()
}
var once sync.Once
return func() {
once.Do(func() {
for i := 0; i < numPath; i++ {
terminate <- true
}
})
}
}
示例12: connectIRC
func (r *Runner) connectIRC() {
conn := irc.IRC(ircNick, ircNick)
conn.UseTLS = true
conn.AddCallback("001", func(*irc.Event) {
conn.Join(ircRoom)
})
var once sync.Once
ready := make(chan struct{})
conn.AddCallback("JOIN", func(*irc.Event) {
once.Do(func() { close(ready) })
})
for {
log.Printf("connecting to IRC server: %s", ircServer)
err := conn.Connect(ircServer)
if err == nil {
break
}
log.Printf("error connecting to IRC server: %s", err)
time.Sleep(time.Second)
}
go conn.Loop()
<-ready
for msg := range r.ircMsgs {
conn.Notice(ircRoom, msg)
}
}
示例13: waitTillNConnections
// waitTillNConnetions will run f which should end up causing the peer with hostPort in ch
// to have the specified number of inbound and outbound connections.
// If the number of connections does not match after a second, the test is failed.
func waitTillNConnections(t *testing.T, ch *Channel, hostPort string, inbound, outbound int, f func()) {
peer, ok := ch.RootPeers().Get(hostPort)
if !ok {
return
}
var (
i = -1
o = -1
)
inboundEmpty := make(chan struct{})
var onUpdateOnce sync.Once
onUpdate := func(p *Peer) {
if i, o = p.NumConnections(); (i == inbound || inbound == -1) &&
(o == outbound || outbound == -1) {
onUpdateOnce.Do(func() {
close(inboundEmpty)
})
}
}
peer.SetOnUpdate(onUpdate)
f()
select {
case <-inboundEmpty:
return
case <-time.After(time.Second):
t.Errorf("Timed out waiting for peer %v to have (in: %v, out: %v) connections, got (in: %v, out: %v)",
hostPort, inbound, outbound, i, o)
}
}
示例14: Serve
func (s *Service) Serve() {
announce := stdsync.Once{}
s.timer.Reset(0)
s.mut.Lock()
s.stop = make(chan struct{})
s.mut.Unlock()
for {
select {
case <-s.timer.C:
if found := s.process(); found != -1 {
announce.Do(func() {
suffix := "s"
if found == 1 {
suffix = ""
}
l.Infoln("Detected", found, "NAT device"+suffix)
})
}
case <-s.stop:
s.timer.Stop()
s.mut.RLock()
for _, mapping := range s.mappings {
mapping.clearAddresses()
}
s.mut.RUnlock()
return
}
}
}
示例15: GetInstance
func (dpf DotProviderFactory) GetInstance(dbSource string) DotProvider {
if dpf.dotProviderMap == nil {
dpf.dotProviderMap = make(map[string]chan DotProvider)
}
_, hasProvider := dpf.dotProviderMap[dbSource]
if !hasProvider {
var once sync.Once
once.Do(func() {
glog.Errorf("Initializing pool for %s", dbSource)
dpf.dotProviderMap[dbSource] = make(chan DotProvider, 20)
for i := 0; i < 20; i++ {
var dotProvider interface{}
dotProvider = &DotProviderDB{}
dotProvider.(DotProvider).Init(dbSource)
dpf.dotProviderMap[dbSource] <- dotProvider.(DotProvider)
}
glog.Errorf("Done initializing pool for %s", dbSource)
})
}
dotProviderFound := <-dpf.dotProviderMap[dbSource]
return dotProviderFound
}