本文整理匯總了Golang中sync/atomic.LoadUint64函數的典型用法代碼示例。如果您正苦於以下問題:Golang LoadUint64函數的具體用法?Golang LoadUint64怎麽用?Golang LoadUint64使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了LoadUint64函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: TestHandlerBufferSize
func TestHandlerBufferSize(t *testing.T) {
base := BaseHandler{}
base.log = l.WithField("testing", "basehandler_flush")
base.interval = 5
base.maxBufferSize = 100
base.channel = make(chan metric.Metric)
base.collectorEndpoints = map[string]CollectorEnd{
"collector1": CollectorEnd{make(chan metric.Metric), 3},
}
emitFunc := func(metrics []metric.Metric) bool {
assert.Equal(t, 3, len(metrics))
return true
}
go base.run(emitFunc)
base.CollectorEndpoints()["collector1"].Channel <- metric.New("testMetric")
base.CollectorEndpoints()["collector1"].Channel <- metric.New("testMetric1")
base.CollectorEndpoints()["collector1"].Channel <- metric.New("testMetric2")
time.Sleep(1 * time.Second)
assert.Equal(t, uint64(3), atomic.LoadUint64(&base.metricsSent))
assert.Equal(t, uint64(0), atomic.LoadUint64(&base.metricsDropped))
// This is just to stop goroutines that have been started before
base.channel <- metric.Metric{}
base.CollectorEndpoints()["collector1"].Channel <- metric.Metric{}
}
示例2: StatusUpdate
func (t *tracker) StatusUpdate() {
shardCount := atomic.LoadUint64(&t.stats.CompletedShards)
pointCount := atomic.LoadUint64(&t.stats.PointsRead)
pointWritten := atomic.LoadUint64(&t.stats.PointsWritten)
log.Printf("Still Working: Completed Shards: %d/%d Points read/written: %d/%d", shardCount, len(t.shards), pointCount, pointWritten)
}
示例3: Stat
func (h *Hub) Stat(details bool) *HubStat {
h.mutex.RLock()
defer h.mutex.RUnlock()
stat := &HubStat{
Rooms: len(h.roomTable),
Connections: len(h.connectionTable),
Sessions: len(h.sessionTable),
Count: h.count,
BroadcastChatMessages: atomic.LoadUint64(&h.broadcastChatMessages),
UnicastChatMessages: atomic.LoadUint64(&h.unicastChatMessages),
}
if details {
rooms := make(map[string][]string)
for roomid, room := range h.roomTable {
sessions := make([]string, 0, len(room.connections))
for id := range room.connections {
sessions = append(sessions, id)
}
rooms[roomid] = sessions
}
stat.IdsInRoom = rooms
sessions := make(map[string]*DataSession)
for sessionid, session := range h.sessionTable {
sessions[sessionid] = session.Data()
}
stat.SessionsById = sessions
connections := make(map[string]string)
for id, connection := range h.connectionTable {
connections[fmt.Sprintf("%d", connection.Idx)] = id
}
stat.ConnectionsByIdx = connections
}
return stat
}
示例4: monitor
func (z *zeroSum) monitor(d time.Duration) {
start := timeutil.Now()
lastTime := start
var lastOps uint64
for ticks := 0; true; ticks++ {
time.Sleep(d)
if ticks%20 == 0 {
fmt.Printf("_elapsed__accounts_________ops__ops/sec___errors___splits____xfers___ranges_____________replicas\n")
}
now := timeutil.Now()
elapsed := now.Sub(lastTime).Seconds()
ops := atomic.LoadUint64(&z.stats.ops)
z.ranges.Lock()
ranges, replicas := z.ranges.count, z.ranges.replicas
z.ranges.Unlock()
fmt.Printf("%8s %9d %11d %8.1f %8d %8d %8d %8d %20s\n",
time.Duration(now.Sub(start).Seconds()+0.5)*time.Second,
z.accountsLen(), ops, float64(ops-lastOps)/elapsed,
atomic.LoadUint64(&z.stats.errors),
atomic.LoadUint64(&z.stats.splits),
atomic.LoadUint64(&z.stats.transfers),
ranges, z.formatReplicas(replicas))
lastTime = now
lastOps = ops
}
}
示例5: getAllGauges
func getAllGauges() ([]IntMetric, []FloatMetric) {
numIDs := int(atomic.LoadUint32(curIntGaugeID))
retint := make([]IntMetric, numIDs)
for i := 0; i < numIDs; i++ {
retint[i] = IntMetric{
Name: intgnames[i],
Val: atomic.LoadUint64(&intgauges[i]),
Tgs: intgtags[i],
}
}
numIDs = int(atomic.LoadUint32(curFloatGaugeID))
retfloat := make([]FloatMetric, numIDs)
for i := 0; i < numIDs; i++ {
// The int64 bit pattern of the float value needs to be converted back
// into a float64 here. This is a literal reinterpretation of the same
// exact bits.
intval := atomic.LoadUint64(&floatgauges[i])
retfloat[i] = FloatMetric{
Name: floatgnames[i],
Val: math.Float64frombits(intval),
Tgs: floatgtags[i],
}
}
return retint, retfloat
}
示例6: managedLogError
// mangedLogError will take an error and log it to the host, depending on the
// type of error and whether or not the DEBUG flag has been set.
func (h *Host) managedLogError(err error) {
// Determine the type of error and the number of times that this error has
// been logged.
var num uint64
var probability int // Error will be logged with 1/probability chance.
switch err.(type) {
case ErrorCommunication:
num = atomic.LoadUint64(&h.atomicCommunicationErrors)
probability = errorCommunicationProbability
case ErrorConnection:
num = atomic.LoadUint64(&h.atomicConnectionErrors)
probability = errorConnectionProbability
case ErrorConsensus:
num = atomic.LoadUint64(&h.atomicConsensusErrors)
probability = errorConsensusProbability
case ErrorInternal:
num = atomic.LoadUint64(&h.atomicInternalErrors)
probability = errorInternalProbability
default:
num = atomic.LoadUint64(&h.atomicNormalErrors)
probability = errorNormalProbability
}
// If num > logFewLimit, substantially decrease the probability that the error
// gets logged.
if num > logFewLimit {
probability = probability * 25
}
// If we've seen less than logAllLimit of that type of error before, log
// the error as a normal logging statement. Otherwise, probabilistically
// log the statement. In debugging mode, log all statements.
logged := false
rand, randErr := crypto.RandIntn(probability + 1)
if randErr != nil {
h.log.Critical("random number generation failed")
}
if num < logAllLimit || rand == probability {
logged = true
h.log.Println(err)
} else {
h.log.Debugln(err)
}
// If the error was logged, increment the log counter.
if logged {
switch err.(type) {
case ErrorCommunication:
atomic.AddUint64(&h.atomicCommunicationErrors, 1)
case ErrorConnection:
atomic.AddUint64(&h.atomicConnectionErrors, 1)
case ErrorConsensus:
atomic.AddUint64(&h.atomicConsensusErrors, 1)
case ErrorInternal:
atomic.AddUint64(&h.atomicInternalErrors, 1)
default:
atomic.AddUint64(&h.atomicNormalErrors, 1)
}
}
}
示例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: metrics
func (v *signatureVerifier) metrics() []instrumentation.Metric {
return []instrumentation.Metric{
instrumentation.Metric{Name: "missingSignatureErrors", Value: atomic.LoadUint64(&v.missingSignatureErrorCount)},
instrumentation.Metric{Name: "invalidSignatureErrors", Value: atomic.LoadUint64(&v.invalidSignatureErrorCount)},
instrumentation.Metric{Name: "validSignatures", Value: atomic.LoadUint64(&v.validSignatureCount)},
}
}
示例9: collectMinersStats
func (s *ProxyServer) collectMinersStats() (int64, int, []interface{}) {
now := util.MakeTimestamp()
var result []interface{}
totalHashrate := int64(0)
totalOnline := 0
for m := range s.miners.Iter() {
stats := make(map[string]interface{})
lastBeat := m.Val.getLastBeat()
hashrate := m.Val.hashrate()
totalHashrate += hashrate
stats["name"] = m.Key
stats["hashrate"] = hashrate
stats["lastBeat"] = lastBeat
stats["validShares"] = atomic.LoadUint64(&m.Val.validShares)
stats["invalidShares"] = atomic.LoadUint64(&m.Val.invalidShares)
stats["validBlocks"] = atomic.LoadUint64(&m.Val.validBlocks)
stats["invalidBlocks"] = atomic.LoadUint64(&m.Val.invalidBlocks)
stats["ip"] = m.Val.IP
if now-lastBeat > (int64(s.timeout/2) / 1000000) {
stats["warning"] = true
}
if now-lastBeat > (int64(s.timeout) / 1000000) {
stats["timeout"] = true
} else {
totalOnline++
}
result = append(result, stats)
}
return totalHashrate, totalOnline, result
}
示例10: Dequeue
// Dequeue removes and returns the `oldest` element from the ring buffer
// It also returns true if the operation is successful, false otherwise
// It blocks on an empty queue
func (rb *RingBuffer) Dequeue() (data interface{}, b bool) {
var cell *ring_cell
pos := atomic.LoadUint64(&rb.dequeue_pos_)
i := 0
Loop:
for {
cell = rb.buffer_[pos&rb.buffer_mask_]
seq := atomic.LoadUint64(&cell.sequence_)
switch dif := seq - pos - 1; {
case dif == 0:
if atomic.CompareAndSwapUint64(&rb.dequeue_pos_, pos, pos+1) {
break Loop
}
case dif < 0:
return nil, false
default:
pos = atomic.LoadUint64(&rb.dequeue_pos_)
}
// freeup the cpu
if i >= freeup_threshold {
runtime.Gosched()
i = 0
} else {
i++
}
}
data = cell.data_
atomic.StoreUint64(&cell.sequence_, pos+rb.buffer_mask_+1)
b = true
return data, b
}
示例11: Enqueue
// Enqueue adds a new element to the tail of the ring buffer
// It returns true if the operation is successful, false otherwise
// It blocks on a full queue
func (rb *RingBuffer) Enqueue(data interface{}) bool {
var cell *ring_cell
pos := atomic.LoadUint64(&rb.enqueue_pos_)
i := 0
Loop:
for {
cell = rb.buffer_[pos&rb.buffer_mask_]
seq := atomic.LoadUint64(&cell.sequence_)
switch dif := seq - pos; {
case dif == 0:
if atomic.CompareAndSwapUint64(&rb.enqueue_pos_, pos, pos+1) {
break Loop
}
case dif < 0:
return false
default:
pos = atomic.LoadUint64(&rb.enqueue_pos_)
}
// freeup the cpu
if i >= freeup_threshold {
runtime.Gosched()
i = 0
} else {
i++
}
}
cell.data_ = data
atomic.StoreUint64(&cell.sequence_, pos+1)
return true
}
示例12: printLine
func printLine() {
// get
timeNow := time.Now()
nowTotalIndexed := atomic.LoadUint64(&totalIndexed)
nowTotalPlainTextIndexed := atomic.LoadUint64(&totalPlainTextIndexed)
// calculate
curPlainTextIndexed := nowTotalPlainTextIndexed - lastTotalPlainTextIndexed
cumTimeTaken := timeNow.Sub(timeStart)
curTimeTaken := timeNow.Sub(timeLast)
cumMBytes := float64(nowTotalPlainTextIndexed) / 1000000.0
curMBytes := float64(curPlainTextIndexed) / 1000000.0
cumSeconds := float64(cumTimeTaken) / float64(time.Second)
curSeconds := float64(curTimeTaken) / float64(time.Second)
dateNow := timeNow.Format(time.RFC3339)
fmt.Fprintf(statsWriter, "%s,%d,%d,%f,%f\n", dateNow, nowTotalIndexed,
nowTotalPlainTextIndexed, cumMBytes/cumSeconds, curMBytes/curSeconds)
timeLast = timeNow
lastTotalIndexed = nowTotalIndexed
lastTotalPlainTextIndexed = nowTotalPlainTextIndexed
}
示例13: metrics
func (u *dropsondeUnmarshaller) metrics() []instrumentation.Metric {
var metrics []instrumentation.Metric
u.RLock()
for appID, count := range u.logMessageReceiveCounts {
metricValue := atomic.LoadUint64(count)
tags := make(map[string]interface{})
tags["appId"] = appID
metrics = append(metrics, instrumentation.Metric{Name: "logMessageReceived", Value: metricValue, Tags: tags})
}
metricValue := atomic.LoadUint64(u.receiveCounts[events.Envelope_LogMessage])
metrics = append(metrics, instrumentation.Metric{Name: "logMessageTotal", Value: metricValue})
u.RUnlock()
for eventType, counterPointer := range u.receiveCounts {
if eventType == events.Envelope_LogMessage {
continue
}
modifiedEventName := []rune(eventType.String())
modifiedEventName[0] = unicode.ToLower(modifiedEventName[0])
metricName := string(modifiedEventName) + "Received"
metricValue := atomic.LoadUint64(counterPointer)
metrics = append(metrics, instrumentation.Metric{Name: metricName, Value: metricValue})
}
metrics = append(metrics, instrumentation.Metric{
Name: "unmarshalErrors",
Value: atomic.LoadUint64(&u.unmarshalErrorCount),
})
return metrics
}
示例14: TestHandlerRun
func TestHandlerRun(t *testing.T) {
var mu sync.Mutex
base := BaseHandler{}
base.log = l.WithField("testing", "basehandler_run")
base.interval = 1
base.maxBufferSize = 1
base.channel = make(chan metric.Metric)
emitCalled := false
emitFunc := func(metrics []metric.Metric) bool {
assert.Equal(t, 1, len(metrics))
mu.Lock()
defer mu.Unlock()
emitCalled = true
return true
}
// now we are waiting for some metrics
go base.run(emitFunc)
base.channel <- metric.New("testMetric")
time.Sleep(1 * time.Second)
mu.Lock()
assert.True(t, emitCalled)
mu.Unlock()
assert.Equal(t, 1, base.GetEmissionTimesLen())
assert.Equal(t, uint64(1), atomic.LoadUint64(&base.metricsSent))
assert.Equal(t, uint64(0), atomic.LoadUint64(&base.metricsDropped))
assert.Equal(t, uint64(1), atomic.LoadUint64(&base.totalEmissions))
base.channel <- metric.Metric{}
}
示例15: TestManyMessagesSingleSocket
func TestManyMessagesSingleSocket(t *testing.T) {
count := 1000
interval := 100 * time.Microsecond
var serverMsgReceivedCount uint64
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sck, err := NewSocket("test_socket", w, r, func(messageType int, message []byte) {
atomic.AddUint64(&serverMsgReceivedCount, 1)
assert.Equal(t, "You got a message!", string(message))
}, nil)
if err != nil {
t.Error("Error creating websocket:", err)
}
// when a request comes in, start writing lotsa messages to it
go writeLotsaMessages(sck, count, interval)
}))
defer ts.Close()
var clientMsgReceivedCount uint64
client := makeClient(t, ts.URL, "test_client", func(messageType int, message []byte) {
atomic.AddUint64(&clientMsgReceivedCount, 1)
assert.Equal(t, "You got a message!", string(message))
}, nil)
// we opened a client connection, starting sending lotsa messages to the server
go writeLotsaMessages(client, count, interval)
// sleep a bit to let the messages be sent
time.Sleep(3 * time.Second)
assert.Equal(t, uint64(count), atomic.LoadUint64(&clientMsgReceivedCount))
assert.Equal(t, uint64(count), atomic.LoadUint64(&serverMsgReceivedCount))
}