zoukankan      html  css  js  c++  java
  • 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)
    }
  • 相关阅读:
    word break II
    leetcode新题
    tensorflow数据读取过程
    python文本编辑: re.sub-------读取文本,去除指定字符并保存
    Anaconda安装及虚拟环境搭建教程(linux)
    语音合成
    关于Python错误提示: 'str' object is not callable
    语音识别学习阶段性总结(一)
    kaldi学习
    kaldi学习
  • 原文地址:https://www.cnblogs.com/simadongyang/p/14397361.html
Copyright © 2011-2022 走看看