本文整理匯總了Golang中sync/atomic.CompareAndSwapInt32函數的典型用法代碼示例。如果您正苦於以下問題:Golang CompareAndSwapInt32函數的具體用法?Golang CompareAndSwapInt32怎麽用?Golang CompareAndSwapInt32使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了CompareAndSwapInt32函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: SlightlyConcurrentMergeSort
func SlightlyConcurrentMergeSort(data []int) {
var activeWorkers int32
var aux func([]int)
aux = func(data []int) {
if len(data) <= 1 {
return
}
pivot := len(data) / 2
left := append([]int{}, data[:pivot]...)
right := append([]int{}, data[pivot:]...)
curActiveWorkers := atomic.LoadInt32(&activeWorkers)
if curActiveWorkers < int32(runtime.NumCPU()) && atomic.CompareAndSwapInt32(&activeWorkers, curActiveWorkers, curActiveWorkers+1) {
var wg sync.WaitGroup
wg.Add(1)
go func() {
aux(left)
wg.Done()
}()
aux(right)
wg.Wait()
} else {
MergeSort(left)
MergeSort(right)
}
Merge(data, left, right)
curActiveWorkers = atomic.LoadInt32(&activeWorkers)
atomic.CompareAndSwapInt32(&activeWorkers, curActiveWorkers, curActiveWorkers-1)
}
aux(data)
}
示例2: stop
func (self *supervisorWithPidfile) stop() {
if 1 != atomic.LoadInt32(&self.owner) {
atomic.CompareAndSwapInt32(&self.srv_status, SRV_RUNNING, SRV_INIT)
self.logString("[sys] ignore process\r\n")
self.logString("[sys] ==================== srv end ====================\r\n")
return
}
defer func() {
if o := recover(); nil != o {
self.last_error = errors.New(fmt.Sprint(o))
} else {
self.last_error = nil
}
}()
if !atomic.CompareAndSwapInt32(&self.srv_status, SRV_RUNNING, SRV_STOPPING) &&
!atomic.CompareAndSwapInt32(&self.srv_status, SRV_STARTING, SRV_STOPPING) {
return
}
self.interrupt()
atomic.CompareAndSwapInt32(&self.srv_status, SRV_STOPPING, PROC_INIT)
atomic.StoreInt32(&self.owner, 0)
self.logString("[sys] ==================== srv end ====================\r\n")
}
示例3: Run
func (r *RunnaStyle) Run(f Runnable) {
if atomic.CompareAndSwapInt32(&r.sem, 0, 1) {
go func() {
ticker := time.NewTicker(r.RunInterval)
defer ticker.Stop()
fmt.Println("let's run")
var idle int32 = 0
for {
if atomic.LoadInt32(&r.sem) == -1 {
return
}
<-ticker.C
if f() {
idle = 0
} else {
idle++
}
if idle >= r.maxidle {
fmt.Println("idle for", idle)
break
}
}
atomic.CompareAndSwapInt32(&r.sem, 1, 0)
}()
} else {
fmt.Println("already running")
}
}
示例4: prodConsSwap
func prodConsSwap() {
wg := new(sync.WaitGroup)
n := 1000000
var lock int32 // Global.
atomic.StoreInt32(&lock, 0)
wg.Add(1)
go func() {
for i := 0; i < n; i++ {
for !atomic.CompareAndSwapInt32(&lock, 0, 1) {
}
counter++
atomic.StoreInt32(&lock, 0)
}
wg.Done()
}()
wg.Add(1)
go func() {
for i := 0; i < n; i++ {
for !atomic.CompareAndSwapInt32(&lock, 0, 1) {
}
counter--
atomic.StoreInt32(&lock, 0)
}
wg.Done()
}()
wg.Wait()
}
示例5: peerConnect
// Creates direct connection to caller to speed response time.
func (s *session) peerConnect(peer string) error {
s.connMapLock.RLock()
if _, ok := s.connMap[peer]; ok {
s.connMapLock.RUnlock()
return nil
}
s.connMapLock.RUnlock()
if !atomic.CompareAndSwapInt32(&s.peerLock, 0, 1) {
return nil
}
defer atomic.CompareAndSwapInt32(&s.peerLock, 1, 0)
socketf := fmt.Sprintf("%s.%s", s.socketf, peer)
conn, err := net.Dial("unix", socketf)
if err != nil {
return err
}
c := s.addconnection(conn)
// Forgo logging on peer connection.
go func() {
if err := c.reciever(); err != nil && err != ErrClosed {
s.log.Println(err)
}
}()
return nil
}
示例6: clean
func (b *Buffer) clean() {
if b.cleanLock == 1 || !atomic.CompareAndSwapInt32(&b.cleanLock, 0, 1) {
return
}
if b.voteCount >= b.peerCount {
for {
if atomic.CompareAndSwapInt32(&b.voteLock, 0, 1) {
b.peerTail = b.nextPeerTail
b.voteCount = 0
b.voteRound++
b.voteLock = 0
break
}
}
}
for b.tail != b.peerTail {
b.values[b.tail] = nil
b.tail++
if b.tail > b.maxIdx {
b.tail = 0
}
}
b.cleanLock = 0
}
示例7: updateQueryCache
func (a *HotActor) updateQueryCache(t time.Time) error {
defer atomic.CompareAndSwapInt32(&a.queryCacheUpdated, 1, 0)
if !atomic.CompareAndSwapInt32(&a.queryCacheUpdated, 0, 1) {
return nil
}
if (t.Unix() - a.lastQueryCacheUpdate.Unix()) < GOAT_UPDATE_SPAN_SEC {
return nil
}
qcsize := len(a.queryDurations)
a.wg = utils.NewWaitGroup(2 * qcsize) //hot and flame
var from time.Time
for i := 0; i < qcsize; i++ {
if a.queryDurations[i] > 0 {
from = t.Add(-1 * a.queryDurations[i])
} else {
from = time.Time{}
}
go a.updateQueryCacheTask(from, t, proto.TopicListRequest_Hot, &a.hotQueryCache[i], a.wg)
go a.updateQueryCacheTask(from, t, proto.TopicListRequest_Flame, &a.flameQueryCache[i], a.wg)
}
if err := a.wg.Wait(); err != nil {
log.Printf("update fails with %v", err)
a.available = false
return err
} else {
log.Printf("update success")
a.available = true
a.lastQueryCacheUpdate = t
}
return nil
}
示例8: GetMsgNum
// 獲取uuid的離線消息數量
func GetMsgNum(uuid string) int {
var (
n int
err error
)
if atomic.CompareAndSwapInt32(&offlinemsg_readMark1, 0, 1) {
n, err = redis.Int(offlinemsg_readCon1.Do("LLEN", uuid))
atomic.StoreInt32(&offlinemsg_readMark1, 0)
} else if atomic.CompareAndSwapInt32(&offlinemsg_readMark2, 0, 1) {
n, err = redis.Int(offlinemsg_readCon2.Do("LLEN", uuid))
atomic.StoreInt32(&offlinemsg_readMark2, 0)
} else if atomic.CompareAndSwapInt32(&offlinemsg_readMark3, 0, 1) {
n, err = redis.Int(offlinemsg_readCon3.Do("LLEN", uuid))
atomic.StoreInt32(&offlinemsg_readMark3, 0)
} else if atomic.CompareAndSwapInt32(&offlinemsg_readMark4, 0, 1) {
n, err = redis.Int(offlinemsg_readCon4.Do("LLEN", uuid))
atomic.StoreInt32(&offlinemsg_readMark4, 0)
}
if err != nil {
return 0
}
return n
}
示例9: Put
func (bl *BufferListener) Put(value []byte) {
b := bl.buffer
tempSlice := make([]byte, len(value))
copy(tempSlice, value)
for {
putIdx := b.putReserve
newIdx := putIdx + 1
if int(newIdx) > b.maxIdx {
newIdx = 0
}
for int(newIdx) == b.tail {
b.clean()
}
if atomic.CompareAndSwapInt32(&b.putReserve, putIdx, newIdx) {
b.values[putIdx] = tempSlice
for {
temp := b.head
if atomic.CompareAndSwapInt32(&b.head, temp, newIdx) {
break
}
}
break
}
}
b.clean()
}
示例10: restart
// start first negotiation
// start n-1 data tun
func (c *Client) restart() (tun *Conn, rn int32) {
if atomic.CompareAndSwapInt32(&c.restarting, 0, 1) {
// discard old conn retrying
c.pendingConn.clearAll()
// discard requests are waiting for tokens
c.pendingTK.clearAll()
// release mux
if c.mux != nil {
c.mux.destroy()
}
c.mux = newClientMultiplexer()
// try negotiating connection infinitely until success
for i := 0; tun == nil; i++ {
if i > 0 {
time.Sleep(RETRY_INTERVAL)
}
tun = c.initialNegotiation()
}
atomic.CompareAndSwapInt32(&c.restarting, 1, 0)
atomic.CompareAndSwapInt32(&c.State, CLT_PENDING, CLT_WORKING)
rn = atomic.AddInt32(&c.round, 1)
for j := c.tp.parallels; j > 1; j-- {
go c.StartTun(false)
}
}
return
}
示例11: gc
//gc dupnodelist
func (t *Btree) gc() {
for {
t.Lock()
if atomic.CompareAndSwapInt32(&t.state, StateNormal, StateGc) {
if len(t.dupnodelist) > 0 {
id := t.dupnodelist[len(t.dupnodelist)-1]
switch t.nodes[id].(type) {
case *Node:
*t.NodeCount--
case *Leaf:
*t.LeafCount--
default:
atomic.CompareAndSwapInt32(&t.state, StateGc, StateNormal)
continue
}
t.FreeList = append(t.FreeList, id)
t.dupnodelist = t.dupnodelist[:len(t.dupnodelist)-1]
atomic.CompareAndSwapInt32(&t.state, StateGc, StateNormal)
}
} else {
time.Sleep(time.Second)
}
t.Unlock()
}
}
示例12: GetLength
// 返回名稱為key的list的長度
func (this *RedisListHelper) GetLength(key string) int {
var (
n int
err error
)
if atomic.CompareAndSwapInt32(&this.readMark1, 0, 1) {
n, err = redis.Int(this.readCon1.Do("LLEN", key))
atomic.StoreInt32(&this.readMark1, 0)
} else if atomic.CompareAndSwapInt32(&this.readMark2, 0, 1) {
n, err = redis.Int(this.readCon2.Do("LLEN", key))
atomic.StoreInt32(&this.readMark2, 0)
} else if atomic.CompareAndSwapInt32(&this.readMark3, 0, 1) {
n, err = redis.Int(this.readCon3.Do("LLEN", key))
atomic.StoreInt32(&this.readMark3, 0)
} else if atomic.CompareAndSwapInt32(&this.readMark4, 0, 1) {
n, err = redis.Int(this.readCon4.Do("LLEN", key))
atomic.StoreInt32(&this.readMark4, 0)
}
if err != nil {
return 0
}
return n
}
示例13: writerRoutine
func (pc *SocketClient) writerRoutine() {
writerloop:
for {
switch atomic.LoadInt32(&pc.state) {
case SocketClosed:
pc.changes.Lock()
for _, v := range pc.queue {
v.responseChan <- ErrShutdown
}
pc.changes.Unlock()
break writerloop
case SocketOpen:
//log.Printf("[SocketClient] Writer state: Open")
request := pc.writeQueueHead
if request == nil {
select {
case request = <-pc.writeQueue:
pc.writeQueueHead = request
if request == nil {
continue
}
case <-time.After(1 * time.Second):
continue
}
}
_, err := pc.conn.Write(request.request)
if err != nil {
log.Printf("[SocketClient] Write failed: %s", err.Error())
atomic.CompareAndSwapInt32(&pc.state, SocketOpen, SocketReconnecting)
} else {
//log.Printf("[SocketClient] Wrote: %s", request.request)
pc.writeQueueHead = nil
request.sent = true
}
case SocketReconnecting:
//log.Printf("[SocketClient] Writer state: Recon")
pc.changes.Lock()
conn, err := net.DialTCP(pc.address.Network(), nil, pc.address)
if err == nil {
pc.reader = bufio.NewReader(conn)
pc.conn = conn
sentshit := make([]int64, 0, 32)
for k, v := range pc.queue {
if v.sent {
v.responseChan <- ErrReconnect
sentshit = append(sentshit, k)
}
}
for _, k := range sentshit {
delete(pc.queue, k)
}
atomic.CompareAndSwapInt32(&pc.state, SocketReconnecting, SocketOpen)
} else {
log.Printf("[SocketClient] Reconnect failed: %s", err.Error())
time.Sleep(5 * time.Second)
}
pc.changes.Unlock()
}
}
}
示例14: Stop
func (this *Writer) Stop() {
if !atomic.CompareAndSwapInt32(&this.stopFlag, 0, 1) {
return
}
if atomic.CompareAndSwapInt32(&this.state, StateConnected, StateDisconnected) {
this.Close()
}
close(this.exitChan)
}
示例15: ListenAndServe
// ListenAndServe listents to connections on the URI requested, and handles any
// incoming MQTT client sessions. It should not return until Close() is called
// or if there's some critical error that stops the server from running. The URI
// supplied should be of the form "protocol://host:port" that can be parsed by
// url.Parse(). For example, an URI could be "tcp://0.0.0.0:1883".
func (this *Server) ListenAndServe(uri string) error {
defer atomic.CompareAndSwapInt32(&this.running, 1, 0)
if !atomic.CompareAndSwapInt32(&this.running, 0, 1) {
return fmt.Errorf("server/ListenAndServe: Server is already running")
}
this.quit = make(chan struct{})
u, err := url.Parse(uri)
if err != nil {
return err
}
this.ln, err = net.Listen(u.Scheme, u.Host)
if err != nil {
return err
}
defer this.ln.Close()
glog.Infof("server/ListenAndServe: server is ready...")
var tempDelay time.Duration // how long to sleep on accept failure
for {
conn, err := this.ln.Accept()
if err != nil {
// http://zhen.org/blog/graceful-shutdown-of-go-net-dot-listeners/
select {
case <-this.quit:
return nil
default:
}
// Borrowed from go1.3.3/src/pkg/net/http/server.go:1699
if ne, ok := err.(net.Error); ok && ne.Temporary() {
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
tempDelay *= 2
}
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
glog.Errorf("server/ListenAndServe: Accept error: %v; retrying in %v", err, tempDelay)
time.Sleep(tempDelay)
continue
}
return err
}
go this.handleConnection(conn)
}
}