本文整理匯總了Golang中sync/atomic.LoadUint32函數的典型用法代碼示例。如果您正苦於以下問題:Golang LoadUint32函數的具體用法?Golang LoadUint32怎麽用?Golang LoadUint32使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了LoadUint32函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: TestRefreshNoChange
func TestRefreshNoChange(t *testing.T) {
var (
addr = &net.SRV{Target: "my-target", Port: 5678}
addrs = []*net.SRV{addr}
name = "my-name"
ticker = time.NewTicker(time.Second)
lookups = uint32(0)
lookupSRV = func(string, string, string) (string, []*net.SRV, error) {
atomic.AddUint32(&lookups, 1)
return "", addrs, nil
}
e = func(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil }
factory = func(string) (endpoint.Endpoint, io.Closer, error) { return e, nil, nil }
logger = log.NewNopLogger()
)
ticker.Stop()
tickc := make(chan time.Time)
ticker.C = tickc
p := NewPublisherDetailed(name, ticker, lookupSRV, factory, logger)
defer p.Stop()
if want, have := uint32(1), atomic.LoadUint32(&lookups); want != have {
t.Errorf("want %d, have %d", want, have)
}
tickc <- time.Now()
if want, have := uint32(2), atomic.LoadUint32(&lookups); want != have {
t.Errorf("want %d, have %d", want, have)
}
}
示例2: testThrottling
func testThrottling(t *testing.T, protocol int) {
// Create a long block chain to download and the tester
targetBlocks := 8 * blockCacheLimit
hashes, blocks := makeChain(targetBlocks, 0, genesis)
tester := newTester()
tester.newPeer("peer", protocol, hashes, blocks)
// Wrap the importer to allow stepping
blocked, proceed := uint32(0), make(chan struct{})
tester.downloader.chainInsertHook = func(blocks []*Block) {
atomic.StoreUint32(&blocked, uint32(len(blocks)))
<-proceed
}
// Start a synchronisation concurrently
errc := make(chan error)
go func() {
errc <- tester.sync("peer", nil)
}()
// Iteratively take some blocks, always checking the retrieval count
for {
// Check the retrieval count synchronously (! reason for this ugly block)
tester.lock.RLock()
retrieved := len(tester.ownBlocks)
tester.lock.RUnlock()
if retrieved >= targetBlocks+1 {
break
}
// Wait a bit for sync to throttle itself
var cached int
for start := time.Now(); time.Since(start) < time.Second; {
time.Sleep(25 * time.Millisecond)
tester.downloader.queue.lock.RLock()
cached = len(tester.downloader.queue.blockPool)
tester.downloader.queue.lock.RUnlock()
if cached == blockCacheLimit || len(tester.ownBlocks)+cached+int(atomic.LoadUint32(&blocked)) == targetBlocks+1 {
break
}
}
// Make sure we filled up the cache, then exhaust it
time.Sleep(25 * time.Millisecond) // give it a chance to screw up
if cached != blockCacheLimit && len(tester.ownBlocks)+cached+int(atomic.LoadUint32(&blocked)) != targetBlocks+1 {
t.Fatalf("block count mismatch: have %v, want %v (owned %v, target %v)", cached, blockCacheLimit, len(tester.ownBlocks), targetBlocks+1)
}
// Permit the blocked blocks to import
if atomic.LoadUint32(&blocked) > 0 {
atomic.StoreUint32(&blocked, uint32(0))
proceed <- struct{}{}
}
}
// Check that we haven't pulled more blocks than available
if len(tester.ownBlocks) > targetBlocks+1 {
t.Fatalf("target block count mismatch: have %v, want %v", len(tester.ownBlocks), targetBlocks+1)
}
if err := <-errc; err != nil {
t.Fatalf("block synchronization failed: %v", err)
}
}
示例3: Release
// Release the peer connection certifying that we are done with it.
func (p *PeerResponse) Release() {
ref := atomic.LoadUint32(&p.peer.refCount)
// Decrement ownership
for ref > 0 && atomic.CompareAndSwapUint32(&p.peer.refCount, ref, ref-1) == false {
ref = atomic.LoadUint32(&p.peer.refCount)
}
}
示例4: TestPoolGC
// Test that Pool does not hold pointers to previously cached
// resources
func TestPoolGC(t *testing.T) {
var p Pool
var fin uint32
const N = 100
for i := 0; i < N; i++ {
v := new(int)
runtime.SetFinalizer(v, func(vv *int) {
atomic.AddUint32(&fin, 1)
})
p.Put(v)
}
for i := 0; i < N; i++ {
p.Get()
}
for i := 0; i < 5; i++ {
runtime.GC()
time.Sleep(time.Millisecond)
// 2 pointers can remain on stack or elsewhere
if atomic.LoadUint32(&fin) >= N-2 {
return
}
}
t.Fatalf("only %v out of %v resources are finalized",
atomic.LoadUint32(&fin), N)
}
示例5: doCheckpoint
// save stat
func (p *Whisper) doCheckpoint() {
updateOperations := atomic.LoadUint32(&p.updateOperations)
commitedPoints := atomic.LoadUint32(&p.commitedPoints)
atomic.AddUint32(&p.updateOperations, -updateOperations)
atomic.AddUint32(&p.commitedPoints, -commitedPoints)
created := atomic.LoadUint32(&p.created)
atomic.AddUint32(&p.created, -created)
logrus.WithFields(logrus.Fields{
"updateOperations": int(updateOperations),
"commitedPoints": int(commitedPoints),
"created": int(created),
}).Info("[persister] doCheckpoint()")
p.Stat("updateOperations", float64(updateOperations))
p.Stat("commitedPoints", float64(commitedPoints))
if updateOperations > 0 {
p.Stat("pointsPerUpdate", float64(commitedPoints)/float64(updateOperations))
} else {
p.Stat("pointsPerUpdate", 0.0)
}
p.Stat("created", float64(created))
}
示例6: gc
func (c *LRUCache) gc() {
time.Sleep(30 * time.Second)
ms := new(runtime.MemStats)
var gcFactor uint32 = 0
for {
runtime.ReadMemStats(ms)
// update gc factor
if ms.HeapAlloc < c.configuration.size {
// stop gc only when cache < 90% of cache limit.
if gcFactor != 0 && ms.HeapAlloc < uint64(0.9*float64(c.configuration.size)) {
c.setGcFactor(0)
gcFactor = 0
}
} else {
if gcFactor == 0 || gcFactor != atomic.LoadUint32(&c.gcFactorCfg) {
gcFactor = atomic.LoadUint32(&c.gcFactorCfg)
c.setGcFactor(gcFactor)
}
}
// notify gcing
if gcFactor != 0 && c.configuration.callback != nil {
c.configuration.callback()
}
time.Sleep(10 * time.Second)
}
}
示例7: GetStream
func (s *IDGenerator) GetStream() (int, bool) {
// based closely on the java-driver stream ID generator
// avoid false sharing subsequent requests.
offset := atomic.LoadUint32(&s.offset)
for !atomic.CompareAndSwapUint32(&s.offset, offset, (offset+1)%s.numBuckets) {
offset = atomic.LoadUint32(&s.offset)
}
offset = (offset + 1) % s.numBuckets
for i := uint32(0); i < s.numBuckets; i++ {
pos := int((i + offset) % s.numBuckets)
bucket := atomic.LoadUint64(&s.streams[pos])
if bucket == math.MaxUint64 {
// all streams in use
continue
}
for j := 0; j < bucketBits; j++ {
mask := uint64(1 << streamOffset(j))
if bucket&mask == 0 {
if atomic.CompareAndSwapUint64(&s.streams[pos], bucket, bucket|mask) {
atomic.AddInt32(&s.inuseStreams, 1)
return streamFromBucket(int(pos), j), true
}
bucket = atomic.LoadUint64(&s.streams[offset])
}
}
}
return 0, false
}
示例8: loop
func (t *lockstepBusySim) loop(e *entity) {
lastnotify := t.notify
t.wg.Done()
runtime.Gosched()
for {
notify := atomic.LoadUint32(&t.notify)
backoff := 0
for notify == lastnotify {
if backoff < 5 {
runtime.Gosched()
} else {
time.Sleep(1000)
}
backoff++
notify = atomic.LoadUint32(&t.notify)
}
lastnotify = notify
fn := t.state
if fn == nil {
t.wg.Done()
break
}
fn(e)
t.wg.Done()
}
}
示例9: Connect
// Establishes a new socket connection to the 9P server and creates
// a client object for it. Negotiates the dialect and msize for the
// connection. Returns a Clnt object, or Error.
func Connect(c net.Conn, msize uint32, dotu bool) (*Clnt, error) {
clnt := NewClnt(c, msize, dotu)
ver := "9P2000"
if clnt.Dotu {
ver = "9P2000.u"
}
clntmsize := atomic.LoadUint32(&clnt.Msize)
tc := ninep.NewFcall(clntmsize)
err := ninep.PackTversion(tc, clntmsize, ver)
if err != nil {
return nil, err
}
rc, err := clnt.Rpc(tc)
if err != nil {
return nil, err
}
if rc.Msize < atomic.LoadUint32(&clnt.Msize) {
atomic.StoreUint32(&clnt.Msize, rc.Msize)
}
clnt.Dotu = rc.Version == "9P2000.u" && clnt.Dotu
return clnt, nil
}
示例10: TestPoolGC
// Test that Pool does not hold pointers to previously cached
// resources
func TestPoolGC(t *testing.T) {
var p Pool
var fin uint32
const N = 100
for i := 0; i < N; i++ {
v := new(string)
runtime.SetFinalizer(v, func(vv *string) {
atomic.AddUint32(&fin, 1)
})
p.Put(v)
}
for i := 0; i < N; i++ {
p.Get()
}
for i := 0; i < 5; i++ {
runtime.GC()
time.Sleep(time.Millisecond)
// 1 pointer can remain on stack or elsewhere
if atomic.LoadUint32(&fin) >= N-1 {
return
}
// gccgo has a less precise heap.
if runtime.Compiler == "gccgo" && atomic.LoadUint32(&fin) >= N-5 {
return
}
}
t.Fatalf("only %v out of %v resources are finalized",
atomic.LoadUint32(&fin), N)
}
示例11: TestV2NoRetryEOF
// TestV2NoRetryEOF tests destructive api calls won't retry on a disconnection.
func TestV2NoRetryEOF(t *testing.T) {
defer testutil.AfterTest(t)
// generate an EOF response; specify address so appears first in sorted ep list
lEOF := integration.NewListenerWithAddr(t, fmt.Sprintf("eof:123.%d.sock", os.Getpid()))
defer lEOF.Close()
tries := uint32(0)
go func() {
for {
conn, err := lEOF.Accept()
if err != nil {
return
}
atomic.AddUint32(&tries, 1)
conn.Close()
}
}()
eofURL := integration.UrlScheme + "://" + lEOF.Addr().String()
cli := integration.MustNewHTTPClient(t, []string{eofURL, eofURL}, nil)
kapi := client.NewKeysAPI(cli)
for i, f := range noRetryList(kapi) {
startTries := atomic.LoadUint32(&tries)
if err := f(); err == nil {
t.Errorf("#%d: expected EOF error, got nil", i)
}
endTries := atomic.LoadUint32(&tries)
if startTries+1 != endTries {
t.Errorf("#%d: expected 1 try, got %d", i, endTries-startTries)
}
}
}
示例12: getAllCallbackGauges
func getAllCallbackGauges() ([]IntMetric, []FloatMetric) {
numIDs := int(atomic.LoadUint32(curIntCbID))
retint := make([]IntMetric, numIDs)
for i := 0; i < numIDs; i++ {
retint[i] = IntMetric{
Name: intcbnames[i],
Val: intcallbacks[i](),
Tgs: intcbtags[i],
}
}
numIDs = int(atomic.LoadUint32(curFloatCbID))
retfloat := make([]FloatMetric, numIDs)
for i := 0; i < numIDs; i++ {
retfloat[i] = FloatMetric{
Name: floatcbnames[i],
Val: floatcallbacks[i](),
Tgs: floatcbtags[i],
}
}
return retint, retfloat
}
示例13: TestFastSyncDisabling
// Tests that fast sync gets disabled as soon as a real block is successfully
// imported into the blockchain.
func TestFastSyncDisabling(t *testing.T) {
// Create a pristine protocol manager, check that fast sync is left enabled
pmEmpty := newTestProtocolManagerMust(t, true, 0, nil, nil)
if atomic.LoadUint32(&pmEmpty.fastSync) == 0 {
t.Fatalf("fast sync disabled on pristine blockchain")
}
// Create a full protocol manager, check that fast sync gets disabled
pmFull := newTestProtocolManagerMust(t, true, 1024, nil, nil)
if atomic.LoadUint32(&pmFull.fastSync) == 1 {
t.Fatalf("fast sync not disabled on non-empty blockchain")
}
// Sync up the two peers
io1, io2 := p2p.MsgPipe()
go pmFull.handle(pmFull.newPeer(63, p2p.NewPeer(discover.NodeID{}, "empty", nil), io2))
go pmEmpty.handle(pmEmpty.newPeer(63, p2p.NewPeer(discover.NodeID{}, "full", nil), io1))
time.Sleep(250 * time.Millisecond)
pmEmpty.synchronise(pmEmpty.peers.BestPeer())
// Check that fast sync was disabled
if atomic.LoadUint32(&pmEmpty.fastSync) == 1 {
t.Fatalf("fast sync not disabled after successful synchronisation")
}
}
示例14: synchronise
// synchronise tries to sync up our local block chain with a remote peer.
func (pm *ProtocolManager) synchronise(peer *peer) {
// Short circuit if no peers are available
if peer == nil {
return
}
// Make sure the peer's TD is higher than our own
currentBlock := pm.blockchain.CurrentBlock()
td := pm.blockchain.GetTd(currentBlock.Hash())
pHead, pTd := peer.Head()
if pTd.Cmp(td) <= 0 {
return
}
// Otherwise try to sync with the downloader
mode := downloader.FullSync
if atomic.LoadUint32(&pm.fastSync) == 1 {
mode = downloader.FastSync
}
if err := pm.downloader.Synchronise(peer.id, pHead, pTd, mode); err != nil {
return
}
atomic.StoreUint32(&pm.synced, 1) // Mark initial sync done
// If fast sync was enabled, and we synced up, disable it
if atomic.LoadUint32(&pm.fastSync) == 1 {
// Disable fast sync if we indeed have something in our chain
if pm.blockchain.CurrentBlock().NumberU64() > 0 {
glog.V(logger.Info).Infof("fast sync complete, auto disabling")
atomic.StoreUint32(&pm.fastSync, 0)
}
}
}
示例15: TestPoolGC
// Test that Pool does not hold pointers to previously cached
// resources
func TestPoolGC(t *testing.T) {
var p Pool
var fin uint32
const N = 100
for i := 0; i < N; i++ {
v := new(string)
runtime.SetFinalizer(v, func(vv *string) {
atomic.AddUint32(&fin, 1)
})
p.Put(uint32(i), v)
}
for i := 0; i < N; i++ {
p.Get(uint32(i))
}
for i := 0; i < 5; i++ {
runtime.GC()
time.Sleep(time.Duration(i*100+10) * time.Millisecond)
// 1 pointer can remain on stack or elsewhere
if atomic.LoadUint32(&fin) >= N-1 {
return
}
}
t.Fatalf("only %v out of %v resources are finalized",
atomic.LoadUint32(&fin), N)
}