美文网首页
任务队列

任务队列

作者: funcx | 来源:发表于2019-10-01 18:25 被阅读0次
    package main
    
    import (
        "context"
        "log"
        "sync"
        "time"
    )
    
    func main() {
        tq := NewTaskQueue()
        go tq.PushStart()
        go tq.Start()
        time.Sleep(5 * time.Second)
        log.Println(tq.AllClient())
    }
    
    type mark struct {
        client string
        ctx    context.Context
    }
    
    type taskQueue struct {
        startQueue chan string //要开始任务的帐号
        // stopQueue  chan string //要结束任务的帐号
        marks  []mark //已开启的任务
        markMu sync.Mutex
    }
    
    func NewTaskQueue() *taskQueue {
        return &taskQueue{startQueue: make(chan string, 0)} // stopQueue: make(chan string, 0),
    }
    
    func (tq *taskQueue) AddMark(m mark) {
        tq.markMu.Lock()
        defer tq.markMu.Unlock()
        tq.marks = append(tq.marks, m)
    }
    
    func (tq *taskQueue) RemoveMark(client string) {
        tq.markMu.Lock()
        defer tq.markMu.Unlock()
        // TODO
    }
    
    func (tq *taskQueue) AllClient() []string {
        cs := []string{}
        for _, v := range tq.marks {
            cs = append(cs, v.client)
        }
        return cs
    }
    
    func (tq *taskQueue) PushStart() {
        clients := []string{"c1", "c2", "c3"}
        for _, client := range clients {
            tq.startQueue <- client
            time.Sleep(time.Second)
        }
    }
    
    func (tq *taskQueue) Start() {
        for client := range tq.startQueue {
            tq.AddMark(mark{client: client})
        }
    }
    

    相关文章

      网友评论

          本文标题:任务队列

          本文链接:https://www.haomeiwen.com/subject/eknkpctx.html