本文整理匯總了Golang中sync/atomic.AddUint32函數的典型用法代碼示例。如果您正苦於以下問題:Golang AddUint32函數的具體用法?Golang AddUint32怎麽用?Golang AddUint32使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了AddUint32函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: NewWorker
func NewWorker(fetchers uint64, tc <-chan Archive, rc chan<- Status) *Worker {
w := new(Worker)
w.ID = atomic.AddUint32(&workerID, 1)
w.Targets, w.Report = tc, rc
w.Fetchers = make([]*Fetcher, fetchers)
w.FRequest = make(chan FetchRequest, 30)
w.FResult = make(chan FetchResult, 30*fetchers)
for i := range w.Fetchers {
f := new(Fetcher)
f.ID = atomic.AddUint32(&fetchID, 1)
f.Request = w.FRequest
f.Result = w.FResult
w.Fetchers[i] = f
go w.Fetchers[i].fetch()
}
go w.Watch()
go func() {
for result := range w.FResult {
if !result.Ok {
log.Printf("Fetch error: %s", result.Description)
}
}
}()
return w
}
示例2: ServeConn
// ServeConn serves HTTP requests from the given connection.
//
// ServeConn returns nil if all requests from the c are successfully served.
// It returns non-nil error otherwise.
//
// Connection c must immediately propagate all the data passed to Write()
// to the client. Otherwise requests' processing may hang.
//
// ServeConn closes c before returning.
func (s *Server) ServeConn(c net.Conn) error {
if s.MaxConnsPerIP > 0 {
pic := wrapPerIPConn(s, c)
if pic == nil {
c.Close()
return ErrPerIPConnLimit
}
c = pic
}
n := atomic.AddUint32(&s.concurrency, 1)
if n > uint32(s.getConcurrency()) {
atomic.AddUint32(&s.concurrency, ^uint32(0))
c.Close()
return ErrConcurrencyLimit
}
err := s.serveConn(c)
atomic.AddUint32(&s.concurrency, ^uint32(0))
if err != errHijacked {
err1 := c.Close()
if err == nil {
err = err1
}
} else {
err = nil
}
return err
}
示例3: updateCounters
func (f *Fixer) updateCounters(chains [][]*x509.Certificate, ferrs []*FixError) {
atomic.AddUint32(&f.validChainsProduced, uint32(len(chains)))
var verifyFailed bool
var fixFailed bool
for _, ferr := range ferrs {
switch ferr.Type {
case VerifyFailed:
verifyFailed = true
case FixFailed:
fixFailed = true
}
}
// No errors --> reconstructed
// VerifyFailed --> notReconstructed
// VerifyFailed but no FixFailed --> fixed
// VerifyFailed and FixFailed --> notFixed
if verifyFailed {
atomic.AddUint32(&f.notReconstructed, 1)
// FixFailed error will only be present if a VerifyFailed error is, as
// fixChain() is only called if constructChain() fails.
if fixFailed {
atomic.AddUint32(&f.notFixed, 1)
return
}
atomic.AddUint32(&f.fixed, 1)
return
}
atomic.AddUint32(&f.reconstructed, 1)
}
示例4: GetSeqNum
// GetSeqNum returns a sequence number that is bigger than the previously sequence number by 1.
func (m32 *MonoIncSeqNumGenerator32) GetSeqNum() uint32 {
seq := atomic.AddUint32((*uint32)(m32), 1)
for seq == 0 {
seq = atomic.AddUint32((*uint32)(m32), 1)
}
return seq
}
示例5: handleConnection
func (rcv *TCP) handleConnection(conn net.Conn) {
atomic.AddInt32(&rcv.active, 1)
defer atomic.AddInt32(&rcv.active, -1)
defer conn.Close()
reader := bufio.NewReader(conn)
for {
conn.SetReadDeadline(time.Now().Add(2 * time.Minute))
line, err := reader.ReadBytes('\n')
if err != nil {
if err == io.EOF {
if len(line) > 0 {
logrus.Warningf("[tcp] Unfinished line: %#v", line)
}
} else {
atomic.AddUint32(&rcv.errors, 1)
logrus.Error(err)
}
break
}
if len(line) > 0 { // skip empty lines
if msg, err := points.ParseText(string(line)); err != nil {
atomic.AddUint32(&rcv.errors, 1)
logrus.Info(err)
} else {
atomic.AddUint32(&rcv.metricsReceived, 1)
rcv.out <- msg
}
}
}
}
示例6: doTarget
func doTarget(target string, pkg []string) {
//println("DEBUG ", target, pkg)
if onlyJS && target != "js" {
results <- resChan{string("Target " + target + " ignored"), nil}
return
}
var lastErr error
exe := "bash"
_, err := exec.LookPath(exe)
if err != nil {
switch exe {
default:
panic(" error - executable not found: " + exe)
}
}
out := []byte{}
if target == "all" {
prms := append([]string{"./testtgoall.sh"}, pkg...)
out, lastErr = exec.Command(exe, prms...).CombinedOutput()
} else {
out, lastErr = exec.Command(exe, "./testtgo.sh", target, pkg[0]).CombinedOutput()
}
layout := "%-25s %s"
for n := range pkg {
if lastErr != nil {
//out = append(out, []byte(lastErr.Error())...)
scores[fmt.Sprintf(layout, pkg[n], target)] = "Fail"
atomic.AddUint32(&failures, 1)
} else {
scores[fmt.Sprintf(layout, pkg[n], target)] = "Pass"
atomic.AddUint32(&passes, 1)
}
}
results <- resChan{string(out), lastErr}
}
示例7: getNextSessID
func (mux *SimpleMux) getNextSessID() uint64 {
baseID := atomic.AddUint32(&(mux.nextSessID), 1)
for baseID == 0 {
baseID = atomic.AddUint32(&(mux.nextSessID), 1)
}
return ((uint64(time.Now().Unix()) << 32) | uint64(baseID))
}
示例8: TestCache
func TestCache(t *testing.T) {
iris.ResetDefault()
expectedBodyStr := "Imagine it as a big message to achieve x20 response performance!"
var textCounter, htmlCounter uint32
iris.Get("/text", iris.Cache(func(ctx *iris.Context) {
atomic.AddUint32(&textCounter, 1)
ctx.Text(iris.StatusOK, expectedBodyStr)
}, cacheDuration))
iris.Get("/html", iris.Cache(func(ctx *iris.Context) {
atomic.AddUint32(&htmlCounter, 1)
ctx.HTML(iris.StatusOK, expectedBodyStr)
}, cacheDuration))
e := httptest.New(iris.Default, t)
// test cache on text/plain
if err := runCacheTest(e, "/text", &textCounter, expectedBodyStr, "text/plain"); err != nil {
t.Fatal(err)
}
// text cache on text/html
if err := runCacheTest(e, "/html", &htmlCounter, expectedBodyStr, "text/html"); err != nil {
t.Fatal(err)
}
}
示例9: pickupstreams
func (pool *streampool) pickupstreams(udp bool) []*upstream {
pool.waitforalive()
// pick udp and tcp equally
pool.RLock()
defer pool.RUnlock()
// pick one of each
switch {
case udp && pool.udplen > 0:
rn := int(atomic.AddUint32(&pool.rn, 1) - 1)
return []*upstream{pool.udpool[rn%pool.udplen]}
case pool.tcplen > 0 && pool.udplen > 0:
// pick one of each
rn := int(atomic.AddUint32(&pool.rn, 1) - 1)
return []*upstream{
pool.udpool[rn%pool.udplen],
pool.tcpool[rn%pool.tcplen],
}
case pool.tcplen == 0 || pool.udplen == 0:
// pick 2 alived
rn := int(atomic.AddUint32(&pool.rn, 2) - 2)
return []*upstream{
pool.alived[rn%pool.alvlen],
pool.alived[(rn+1)%pool.alvlen],
}
}
logrus.Warnln("no upstream avalible for pick")
return nil
}
示例10: loadStats
func loadStats(f io.Reader) {
s := bufio.NewScanner(f)
wg := new(sync.WaitGroup)
tmp := make([][]byte, sNum)
unkC = 0
srch := func(b [][]byte) {
for _, v := range b {
t := root.search(convertIP(v))
if t == nil {
atomic.AddUint32(&unkC, 1)
} else {
atomic.AddUint32(&t.count, 1)
}
}
wg.Done()
}
i := 0
for s.Scan() {
tmp[i] = make([]byte, len(s.Bytes()))
copy(tmp[i], s.Bytes())
i++
if i == sNum {
wg.Add(1)
go srch(tmp)
i, tmp = 0, make([][]byte, sNum)
}
}
if i > 0 {
wg.Add(1)
go srch(tmp[:i])
}
wg.Wait()
}
示例11: 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))
}
示例12: TestSemaphoreMultipleGoroutines
func TestSemaphoreMultipleGoroutines(t *testing.T) {
var done uint32
sem := NewSemaphore(0)
sem2 := NewSemaphore(0)
go func() {
sem.Wait()
atomic.AddUint32(&done, 1)
sem2.Post()
}()
go func() {
time.Sleep(10 * time.Nanosecond)
atomic.AddUint32(&done, 1)
sem.Post()
}()
go func() {
time.Sleep(20 * time.Nanosecond)
atomic.AddUint32(&done, 1)
sem.Post()
}()
sem.Wait()
go func() {
time.Sleep(10 * time.Nanosecond)
atomic.AddUint32(&done, 1)
sem.Post()
}()
sem.Wait()
sem2.Wait()
doneVal := atomic.LoadUint32(&done)
if doneVal != 4 {
t.Fatalf("sem.Wait did not wait for sem.Posts")
}
}
示例13: statWorker
func (rcv *UDP) statWorker(exit chan bool) {
ticker := time.NewTicker(rcv.metricInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
metricsReceived := atomic.LoadUint32(&rcv.metricsReceived)
atomic.AddUint32(&rcv.metricsReceived, -metricsReceived)
rcv.Stat("udp.metricsReceived", float64(metricsReceived))
incompleteReceived := atomic.LoadUint32(&rcv.incompleteReceived)
atomic.AddUint32(&rcv.incompleteReceived, -incompleteReceived)
rcv.Stat("udp.incompleteReceived", float64(incompleteReceived))
errors := atomic.LoadUint32(&rcv.errors)
atomic.AddUint32(&rcv.errors, -errors)
rcv.Stat("udp.errors", float64(errors))
logrus.WithFields(logrus.Fields{
"metricsReceived": int(metricsReceived),
"incompleteReceived": int(incompleteReceived),
"errors": int(errors),
}).Info("[udp] doCheckpoint()")
case <-exit:
rcv.conn.Close()
return
}
}
}
示例14: Get
// Get returns existed connection from the pool or creates a new one.
func (p *ConnPool) Get() (*Conn, error) {
if p.Closed() {
return nil, ErrClosed
}
atomic.AddUint32(&p.stats.Requests, 1)
// Fetch first non-idle connection, if available.
if cn := p.First(); cn != nil {
atomic.AddUint32(&p.stats.Hits, 1)
return cn, nil
}
// Try to create a new one.
if p.conns.Reserve() {
cn, err := p.NewConn()
if err != nil {
p.conns.CancelReservation()
return nil, err
}
p.conns.Add(cn)
return cn, nil
}
// Otherwise, wait for the available connection.
atomic.AddUint32(&p.stats.Waits, 1)
if cn := p.wait(); cn != nil {
return cn, nil
}
atomic.AddUint32(&p.stats.Timeouts, 1)
return nil, ErrPoolTimeout
}
示例15: getURL
func (u *urlCache) getURL(url string) ([]byte, error) {
r, ok := u.cache.get(url)
if ok {
atomic.AddUint32(&u.hit, 1)
return r, nil
}
c, err := u.client.Get(url)
if err != nil {
atomic.AddUint32(&u.errors, 1)
return nil, err
}
defer c.Body.Close()
// TODO(katjoyce): Add caching of permanent errors.
if c.StatusCode != 200 {
atomic.AddUint32(&u.badStatus, 1)
return nil, fmt.Errorf("can't deal with status %d", c.StatusCode)
}
r, err = ioutil.ReadAll(c.Body)
if err != nil {
atomic.AddUint32(&u.readFail, 1)
return nil, err
}
atomic.AddUint32(&u.miss, 1)
u.cache.set(url, r)
return r, nil
}