本文整理匯總了Golang中sync/atomic.LoadInt32函數的典型用法代碼示例。如果您正苦於以下問題:Golang LoadInt32函數的具體用法?Golang LoadInt32怎麽用?Golang LoadInt32使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了LoadInt32函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: SetMaxInFlight
// update the reader ready state, updating each connection as appropriate
func (q *Reader) SetMaxInFlight(maxInFlight int) {
if atomic.LoadInt32(&q.stopFlag) == 1 {
return
}
if maxInFlight > MaxReadyCount {
log.Printf("WARNING: tried to SetMaxInFlight() > %d, truncating...", MaxReadyCount)
maxInFlight = MaxReadyCount
}
if q.maxInFlight == maxInFlight {
return
}
q.maxInFlight = maxInFlight
for _, c := range q.nsqConnections {
if atomic.LoadInt32(&c.stopFlag) == 1 {
continue
}
s := q.ConnectionMaxInFlight()
if q.VerboseLogging {
log.Printf("[%s] RDY %d", c, s)
}
atomic.StoreInt64(&c.rdyCount, int64(s))
err := c.sendCommand(Ready(s))
if err != nil {
handleError(q, c, fmt.Sprintf("[%s] error reading response %s", c, err.Error()))
}
}
}
示例2: TestMock_Tick
// Ensure that the mock's Tick channel sends at the correct time.
func TestMock_Tick(t *testing.T) {
var n int32
clock := NewMock()
// Create a channel to increment every 10 seconds.
go func() {
tick := clock.Tick(10 * time.Second)
for {
<-tick
atomic.AddInt32(&n, 1)
}
}()
gosched()
// Move clock forward to just before the first tick.
clock.Add(9 * time.Second)
if atomic.LoadInt32(&n) != 0 {
t.Fatalf("expected 0, got %d", n)
}
// Move clock forward to the start of the first tick.
clock.Add(1 * time.Second)
if atomic.LoadInt32(&n) != 1 {
t.Fatalf("expected 1, got %d", n)
}
// Move clock forward over several ticks.
clock.Add(30 * time.Second)
if atomic.LoadInt32(&n) != 4 {
t.Fatalf("expected 4, got %d", n)
}
}
示例3: ResetElectionTimeoutMs
// ResetElectionTimeoutMs sets the minimum and maximum election timeouts to the
// passed values, and returns the old values.
func ResetElectionTimeoutMs(newMin, newMax int) (int, int) {
oldMin := atomic.LoadInt32(&minimumElectionTimeoutMs)
oldMax := atomic.LoadInt32(&maximumElectionTimeoutMs)
atomic.StoreInt32(&minimumElectionTimeoutMs, int32(newMin))
atomic.StoreInt32(&maximumElectionTimeoutMs, int32(newMax))
return int(oldMin), int(oldMax)
}
示例4: checkLimitsForObtainingNewCerts
// checkLimitsForObtainingNewCerts checks to see if name can be issued right
// now according to mitigating factors we keep track of and preferences the
// user has set. If a non-nil error is returned, do not issue a new certificate
// for name.
func checkLimitsForObtainingNewCerts(name string) error {
// User can set hard limit for number of certs for the process to issue
if onDemandMaxIssue > 0 && atomic.LoadInt32(OnDemandIssuedCount) >= onDemandMaxIssue {
return fmt.Errorf("%s: maximum certificates issued (%d)", name, onDemandMaxIssue)
}
// Make sure name hasn't failed a challenge recently
failedIssuanceMu.RLock()
when, ok := failedIssuance[name]
failedIssuanceMu.RUnlock()
if ok {
return fmt.Errorf("%s: throttled; refusing to issue cert since last attempt on %s failed", name, when.String())
}
// Make sure, if we've issued a few certificates already, that we haven't
// issued any recently
lastIssueTimeMu.Lock()
since := time.Since(lastIssueTime)
lastIssueTimeMu.Unlock()
if atomic.LoadInt32(OnDemandIssuedCount) >= 10 && since < 10*time.Minute {
return fmt.Errorf("%s: throttled; last certificate was obtained %v ago", name, since)
}
// 👍Good to go
return nil
}
示例5: ConnectToNSQLookupd
// ConnectToNSQLookupd adds an nsqlookupd address to the list for this Consumer instance.
//
// If it is the first to be added, it initiates an HTTP request to discover nsqd
// producers for the configured topic.
//
// A goroutine is spawned to handle continual polling.
func (r *Consumer) ConnectToNSQLookupd(addr string) error {
if atomic.LoadInt32(&r.stopFlag) == 1 {
return errors.New("consumer stopped")
}
if atomic.LoadInt32(&r.runningHandlers) == 0 {
return errors.New("no handlers")
}
if err := validatedLookupAddr(addr); err != nil {
return err
}
atomic.StoreInt32(&r.connectedFlag, 1)
r.mtx.Lock()
for _, x := range r.lookupdHTTPAddrs {
if x == addr {
r.mtx.Unlock()
return nil
}
}
r.lookupdHTTPAddrs = append(r.lookupdHTTPAddrs, addr)
numLookupd := len(r.lookupdHTTPAddrs)
r.mtx.Unlock()
// if this is the first one, kick off the go loop
if numLookupd == 1 {
r.queryLookupd()
r.wg.Add(1)
go r.lookupdLoop()
}
return nil
}
示例6: checkSlave
func (n *Node) checkSlave() {
n.RLock()
if n.Slave == nil {
n.RUnlock()
return
}
slaves := make([]*DB, len(n.Slave))
copy(slaves, n.Slave)
n.RUnlock()
for i := 0; i < len(slaves); i++ {
if err := slaves[i].Ping(); err != nil {
golog.Error("Node", "checkSlave", "Ping", 0, "db.Addr", slaves[i].Addr(), "error", err.Error())
} else {
if atomic.LoadInt32(&(slaves[i].state)) == Down {
golog.Info("Node", "checkSlave", "Slave up", 0, "db.Addr", slaves[i].Addr())
n.UpSlave(slaves[i].addr)
}
slaves[i].SetLastPing()
if atomic.LoadInt32(&(slaves[i].state)) != ManualDown {
atomic.StoreInt32(&(slaves[i].state), Up)
}
continue
}
if int64(n.DownAfterNoAlive) > 0 && time.Now().Unix()-slaves[i].GetLastPing() > int64(n.DownAfterNoAlive/time.Second) {
golog.Info("Node", "checkSlave", "Slave down", 0,
"db.Addr", slaves[i].Addr(),
"slave_down_time", int64(n.DownAfterNoAlive/time.Second))
//If can't ping slave after DownAfterNoAlive, set slave Down
n.DownSlave(slaves[i].addr, Down)
}
}
}
示例7: startEventCycle
func (r *RouteFetcher) startEventCycle() {
go func() {
useCachedToken := true
for {
r.logger.Debug("fetching-token")
token, err := r.UaaClient.FetchToken(useCachedToken)
if err != nil {
metrics.IncrementCounter(TokenFetchErrors)
r.logger.Error("failed-to-fetch-token", err)
} else {
r.logger.Debug("token-fetched-successfully")
if atomic.LoadInt32(&r.stopEventSource) == 1 {
return
}
err = r.subscribeToEvents(token)
if err != nil && err.Error() == "unauthorized" {
useCachedToken = false
} else {
useCachedToken = true
}
if atomic.LoadInt32(&r.stopEventSource) == 1 {
return
}
time.Sleep(time.Duration(r.SubscriptionRetryIntervalInSeconds) * time.Second)
}
}
}()
}
示例8: animate
func (elevator *Elevator) animate() {
i := 0
for elevator.getNumScheduledStops() > 0 && i < 100000 {
fmt.Printf(" Moving %s, current floor %d\n", elevator.Direction, *elevator.CurrentFloor)
if elevator.Direction == Up {
if atomic.LoadInt32(elevator.CurrentFloor) < int32(elevator.numFloors-1) {
atomic.AddInt32(elevator.CurrentFloor, 1)
time.Sleep(10 * time.Millisecond)
}
}
if elevator.Direction == Down {
if atomic.LoadInt32(elevator.CurrentFloor) > int32(0) {
atomic.AddInt32(elevator.CurrentFloor, -1)
time.Sleep(10 * time.Millisecond)
}
}
if elevator.scheduledStops[*elevator.CurrentFloor] == 1 {
fmt.Printf("Visiting floor %d\n", *elevator.CurrentFloor)
elevator.descheduleStop(*elevator.CurrentFloor)
}
i = i + 1
}
if i >= 100000 {
panic("Something is really wrong, elevator went cuckoo")
}
elevator.stopElevator()
}
示例9: CheckHang
// prints message every second until returned thunk is executed.
// useful for determining what function calls are hanging.
func CheckHang(message string, args ...interface{}) func() {
done := int32(0)
go func() {
// do nothing if done is called quickly; reduces printed messages
time.Sleep(1000 * time.Millisecond)
if atomic.LoadInt32(&done) != 0 {
return
}
// loop until done, printing message at each interval
for atomic.LoadInt32(&done) == 0 {
fmt.Printf(message, args...)
fmt.Printf("\t There are %v live goroutines.\n", runtime.NumGoroutine())
time.Sleep(1000 * time.Millisecond)
}
}()
// thunk to be called by client when done
return func() {
atomic.StoreInt32(&done, 1)
}
}
示例10: String
// String implements fmt.Stringer.
func (p *peer) String() string {
return fmt.Sprintf("Peer %s [%s]", p.id,
fmt.Sprintf("reputation %3d, ", atomic.LoadInt32(&p.rep))+
fmt.Sprintf("capacity %3d, ", atomic.LoadInt32(&p.capacity))+
fmt.Sprintf("ignored %4d", p.ignored.Size()),
)
}
示例11: TestRemoveUnits
func (s *S) TestRemoveUnits(c *gocheck.C) {
var calls int32
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
v := atomic.LoadInt32(&calls)
atomic.StoreInt32(&calls, v+1)
w.WriteHeader(http.StatusNoContent)
}))
srvc := service.Service{Name: "mysql", Endpoint: map[string]string{"production": ts.URL}}
err := srvc.Create()
c.Assert(err, gocheck.IsNil)
defer s.conn.Services().Remove(bson.M{"_id": "mysql"})
app := App{
Name: "chemistry",
Framework: "python",
}
instance := service.ServiceInstance{
Name: "my-inst",
ServiceName: "mysql",
Teams: []string{s.team.Name},
Apps: []string{app.Name},
}
instance.Create()
defer s.conn.ServiceInstances().Remove(bson.M{"name": "my-inst"})
err = s.conn.Apps().Insert(app)
c.Assert(err, gocheck.IsNil)
defer s.conn.Apps().Remove(bson.M{"name": app.Name})
c.Assert(err, gocheck.IsNil)
s.provisioner.Provision(&app)
defer s.provisioner.Destroy(&app)
app.AddUnits(4)
otherApp := App{Name: app.Name, Units: app.Units}
err = otherApp.RemoveUnits(2)
c.Assert(err, gocheck.IsNil)
ts.Close()
units := s.provisioner.GetUnits(&app)
c.Assert(units, gocheck.HasLen, 3) // when you provision you already have one, so it's 4+1-2 (in provisioner, in app struct we have 2)
c.Assert(units[0].Name, gocheck.Equals, "chemistry/0")
c.Assert(units[1].Name, gocheck.Equals, "chemistry/3")
c.Assert(units[2].Name, gocheck.Equals, "chemistry/4")
err = app.Get()
c.Assert(err, gocheck.IsNil)
c.Assert(app.Framework, gocheck.Equals, "python")
c.Assert(app.Units, gocheck.HasLen, 2)
c.Assert(app.Units[0].Name, gocheck.Equals, "chemistry/3")
c.Assert(app.Units[1].Name, gocheck.Equals, "chemistry/4")
ok := make(chan int8)
go func() {
for _ = range time.Tick(1e3) {
if atomic.LoadInt32(&calls) == 2 {
ok <- 1
return
}
}
}()
select {
case <-ok:
case <-time.After(2e9):
c.Fatal("Did not call service endpoint twice.")
}
}
示例12: Ticks
// returns ticks of current and previous seconds
func (t *QpsTracker) Ticks() (c1, e1, c2, e2 int32) {
c1 = atomic.LoadInt32(&t.c[int((atomic.LoadInt64(&t.active)+int64(1))%2)])
e1 = atomic.LoadInt32(&t.e[int((atomic.LoadInt64(&t.active)+int64(1))%2)])
c2 = atomic.LoadInt32(&t.c[int((atomic.LoadInt64(&t.active))%2)])
e2 = atomic.LoadInt32(&t.e[int((atomic.LoadInt64(&t.active))%2)])
return
}
示例13: Elect
func (t *testCourse) Elect(k icarus.LoginSession) (bool, error) {
conc := atomic.AddInt32(&t.concurrent, 1)
if conc > 1 && t.noConcurrent {
log.Fatalf("2 goroutines electing at the same time!")
}
defer atomic.AddInt32(&t.concurrent, -1)
if t.forbidden {
log.Fatalf("Entered forbidden elect function.")
}
log.Printf("Electing...Remaining %d, Elected %d", t.remaining, t.elected)
if reflect.TypeOf(k).Name() != "string" {
log.Fatalf("Wrong type of login session.")
}
if k.(string) != session {
log.Fatalf("Wrong value of login session.")
}
atomic.AddInt32(&t.elected, 1)
time.Sleep(time.Duration(rand.Float32()*3000) * time.Millisecond)
if atomic.LoadInt32(&t.errorToMake) > 0 {
atomic.AddInt32(&t.errorToMake, -1)
return false, errors.New("False Alarm")
} else {
if atomic.LoadInt32(&t.remaining) > 0 {
atomic.AddInt32(&t.remaining, -1)
return false, nil
} else {
log.Println("Elected!")
return true, nil
}
}
}
示例14: RLock
func (m *RWMutexTracker) RLock() {
m.logOnce.Do(m.startLogger)
atomic.AddInt32(&m.nwaitr, 1)
// Catch read-write-read lock. See if somebody (us? via
// another goroutine?) already has a read lock, and then
// somebody else is waiting to write, meaning our second read
// will deadlock.
if atomic.LoadInt32(&m.nhaver) > 0 && atomic.LoadInt32(&m.nwaitw) > 0 {
buf := getBuf()
buf = buf[:runtime.Stack(buf, false)]
log.Printf("Potential R-W-R deadlock at: %s", buf)
putBuf(buf)
}
m.mu.RLock()
atomic.AddInt32(&m.nwaitr, -1)
atomic.AddInt32(&m.nhaver, 1)
gid := GoroutineID()
m.hmu.Lock()
defer m.hmu.Unlock()
if m.holdr == nil {
m.holdr = make(map[int64]bool)
}
if m.holdr[gid] {
buf := getBuf()
buf = buf[:runtime.Stack(buf, false)]
log.Fatalf("Recursive call to RLock: %s", buf)
}
m.holdr[gid] = true
}
示例15: ConnectToNSQ
func (q *Reader) ConnectToNSQ(addr string) error {
if atomic.LoadInt32(&q.stopFlag) == 1 {
return errors.New("reader stopped")
}
if atomic.LoadInt32(&q.runningHandlers) == 0 {
return errors.New("no handlers")
}
_, ok := q.nsqConnections[addr]
if ok {
return ErrAlreadyConnected
}
log.Printf("[%s] connecting to nsqd", addr)
connection, err := newNSQConn(addr, q.ReadTimeout, q.WriteTimeout)
if err != nil {
return err
}
err = connection.sendCommand(Subscribe(q.TopicName, q.ChannelName, q.ShortIdentifier, q.LongIdentifier))
if err != nil {
connection.Close()
return fmt.Errorf("[%s] failed to subscribe to %s:%s - %s", q.TopicName, q.ChannelName, err.Error())
}
q.nsqConnections[connection.String()] = connection
go q.readLoop(connection)
go q.finishLoop(connection)
return nil
}