当前位置: 首页>>代码示例>>Golang>>正文


Golang sync.Once类代码示例

本文整理汇总了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
}
开发者ID:hualet,项目名称:golang-workspace,代码行数:30,代码来源:acme.go

示例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()
}
开发者ID:GamerockSA,项目名称:dex,代码行数:30,代码来源:conn_test.go

示例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
}
开发者ID:dvyukov,项目名称:go-conc,代码行数:28,代码来源:once_mutex.go

示例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
}
开发者ID:i,项目名称:paralyze,代码行数:31,代码来源:paralyze.go

示例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
}
开发者ID:quantum1423-dustbin,项目名称:kirisurf-legacy,代码行数:27,代码来源:make_icom.go

示例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)
	}
}
开发者ID:gl-works,项目名称:ringpop-go,代码行数:28,代码来源:peer_test.go

示例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
}
开发者ID:vmware,项目名称:vic,代码行数:31,代码来源:graceful_test.go

示例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
}
开发者ID:jsimonetti,项目名称:tlstun,代码行数:25,代码来源:pipe.go

示例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))
	}
}
开发者ID:CERN-Stage-3,项目名称:vitess,代码行数:33,代码来源:query_engine.go

示例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
}
开发者ID:CubeLite,项目名称:cockroach,代码行数:35,代码来源:context_test.go

示例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
			}
		})
	}
}
开发者ID:kamicup,项目名称:solocounter,代码行数:26,代码来源:Storage.go

示例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)
	}
}
开发者ID:justintung,项目名称:flynn,代码行数:26,代码来源:runner.go

示例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)
	}
}
开发者ID:uber,项目名称:tchannel-go,代码行数:36,代码来源:peer_test.go

示例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
		}
	}
}
开发者ID:carriercomm,项目名称:syncthing,代码行数:32,代码来源:service.go

示例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
}
开发者ID:enjule1,项目名称:enju,代码行数:27,代码来源:dotprovider.go


注:本文中的sync.Once类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。