zoukankan      html  css  js  c++  java
  • Go Example--状态协程

    package main
    
    import (
    	"fmt"
    	"math/rand"
    	"sync/atomic"
    	"time"
    )
    
    type readOp struct {
    	key  int
    	resp chan int
    }
    type writeOp struct {
    	key  int
    	val  int
    	resp chan bool
    }
    
    func main() {
    	var ops int64
    	reads := make(chan *readOp)
    	writes := make(chan *writeOp)
    	go func() {
    		//在该协程中定义的map,通过其他协程来读取数据,因为map不是协程安全的,所以只能一个协程来读取
    		var state = make(map[int]int)
    		for {
    			select {
    			case read := <-reads:
    				read.resp <- state[read.key]
    			case write := <-writes:
    				write.resp <- true
    			}
    		}
    	}()
    	for r := 0; r < 100; r++ {
    		go func() {
    			for {
    				read := &readOp{
    					key:  rand.Intn(5),
    					resp: make(chan int),
    				}
    				reads <- read
    				<-read.resp
    				atomic.AddInt64(&ops, 1)
    			}
    		}()
    	}
    	for w := 0; w < 10; w++ {
    		go func() {
    			for {
    				write := &writeOp{
    					key:  rand.Intn(5),
    					val:  rand.Intn(100),
    					resp: make(chan bool),
    				}
    				writes <- write
    				<-write.resp
    				atomic.AddInt64(&ops, 1)
    			}
    		}()
    	}
    	time.Sleep(time.Second)
    	opsFinal := atomic.LoadInt64(&ops)
    	fmt.Println("ops:", opsFinal)
    }
    
  • 相关阅读:
    python中的字典
    python中的元组操作
    python中的列表
    python中的内建函数
    python中格式化字符串
    34 哈夫曼编码
    33 构造哈夫曼树
    32 哈夫曼树
    31 树和森林的遍历
    30 森林和二叉树的转化(二叉树与多棵树之间的关系)
  • 原文地址:https://www.cnblogs.com/promenader/p/9837013.html
Copyright © 2011-2022 走看看