• go协程池


    package main

    import (
    "fmt"
    "time"
    )
    func main() {
    cap_num := 5

    pool := NewPool(cap_num)
    go func() {
    for {
    task := NewTask(func() {
    fmt.Println(time.Now())
    })
    pool.InChannel <- task
    }
    }()
    //任务调度
    pool.PoolRun()
    }
    type Task struct {
    F func()
    }
    //创建任务
    func NewTask(f func()) *Task {
    task := Task{F:f}
    return &task
    }
    //任务执行
    func (t *Task) TaskRun() {
    t.F()
    }
    //协程池
    type GoroutinePool struct {
    CapNum int
    //进任务的管道
    InChannel chan *Task
    //任务调度的管道
    WorkChannel chan *Task
    }
    func NewPool(cap_num int) *GoroutinePool {
    pool := GoroutinePool{
    CapNum:cap_num,
    InChannel:make(chan *Task),
    WorkChannel: make(chan *Task),
    }
    return &pool
    }
    //从Inchannel管道拿到任务,放到WorkChannel
    func (p *GoroutinePool) TaskInChannelOut() {
    for task := range p.InChannel {
    p.WorkChannel <- task
    }
    }
    //任务执行者从WorkChannel 获取任务并执行
    func (p *GoroutinePool) Worker() {
    for task := range p.WorkChannel {
    task.TaskRun()
    fmt.Println("任务书执行完毕")
    }
    }
    func (p *GoroutinePool) PoolRun() {
    //任务执行
    for i := 0; i < p.CapNum; i++ {
    go p.Worker() //开启指定数量的协程执行任务
    }
    //从InChannel管道拿到任务
    p.TaskInChannelOut()
    close(p.WorkChannel)
    close(p.InChannel)
    }
  • 相关阅读:
    OData的初步认识
    ABP源码分析二十五:EventBus
    ABP源码分析二十四:Notification
    ABP源码分析二十三:Authorization
    ABP源码分析二十二:Navigation
    ABP源码分析二十一:Feature
    160. 相交链表
    83. 删除排序链表中的重复元素
    21. 合并两个有序链表
    字典(dict)常用操作
  • 原文地址:https://www.cnblogs.com/simadongyang/p/14397361.html
Copyright © 2020-2023  润新知