Go 状态协程 Stateful

状态协程

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 readOps uint64
    var writeOps uint64

    reads := make(chan readOp)  //创建一个用于监听读数据的协程
    writes := make(chan writeOp)//创建一个用于监听写数据的协程

	/**
	** 监听所有的读写操作,并反馈结果
	** 这就是拥有 state 的那个协程, 不过这里的 state 是被这个状态协程私有的。
	** 这个协程不断地在 reads 和 writes 通道上进行选择,并在请求到达时做出响应。
	** 首先,执行请求的操作;然后,执行响应,在响应通道 resp 上发送一个值,
	** 表明请求成功(reads 的值则为 state 对应的值)。
	 */
    go func() {
        var state = make(map[int]int)
        for {
            select {
            case read := <-reads:
                read.resp <- state[read.key]// 反馈
            case write := <-writes:
                state[write.key] = write.val//写入state
                write.resp <- true// 反馈
            }
        }
    }()
	/**
	 **  启动 100 个协程通过 reads 通道向拥有 state 的协程发起读取请求。
	 ** 每个读取请求需要构造一个 readOp,发送它到 reads 通道中, 并通过给定的 resp 通道接收结果。
	 */
    for r := 0; r < 100; r++ {
        go func() {
            for {
                read := readOp{
                    key:  rand.Intn(5),
                    resp: make(chan int)}
                reads <- read//向通道发起读
                <-read.resp//等待读结束
                atomic.AddUint64(&readOps, 1)
                time.Sleep(time.Millisecond)
            }
        }()
    }
	// 用相同的方法启动10个写操作。
    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.AddUint64(&writeOps, 1)
                time.Sleep(time.Millisecond)
            }
        }()
    }
	//让程序运行1秒
    time.Sleep(time.Second)

    readOpsFinal := atomic.LoadUint64(&readOps)
    fmt.Println("readOps:", readOpsFinal)
    writeOpsFinal := atomic.LoadUint64(&writeOps)
    fmt.Println("writeOps:", writeOpsFinal)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值