Golang 简易任务分发

Golang 简易的任务分发

package main

import (
    "fmt"
    "sync"
    "time"
)

var workNum int = 3  // 线程池
var ch chan string   // 管道传输
var mutex sync.Mutex // 统计锁
var count int        // 统计正在使用中的线程池

func init() {
    ch = make(chan string, workNum)
    for i := 0; i < workNum; i++ {
        go work(i)
    }
    time.Sleep(time.Second * 1)

}

func main() {
    go func() {
        inputText := []string{
            "001", "002", "003", "004", "005",
        }
        for _, v := range inputText {
            go send(v)
        }
    }()
    for {
        // 后台执行
    }
}

// 发送任务
func send(name string) {
    for {
        if count < workNum {
            mutex.Lock()
            count++
            mutex.Unlock()
            ch <- name // 分发
            break
        }
    }
}

// 处理
func work(i int) {
    fmt.Println("ID", i, "启动")
    for {
        select {
        case n := <-ch:
            fmt.Println("ID", i, n)
            time.Sleep(time.Second * 1)
            mutex.Lock()
            count--
            mutex.Unlock()
            break
        }
    }
}

TAG:GoLang, Go

发表新评论