golang 通过channel控制并发数量

使用 go 关键字有时候需要控制一下并发的数量, 但不至于去修改 runtime.GOMAXPROCS 这个数值, 这里就用到了缓冲channel的特性

demo:


package pool

import (
    "sync"
)

// WaitGroup 一个异步结构体
type WaitGroup struct {
    workChan chan int
    wg       sync.WaitGroup
}

// NewPool 生成一个工作池, coreNum 限制
func NewPool(coreNum int) *WaitGroup {
    ch := make(chan int, coreNum)
    return &WaitGroup{
        workChan: ch,
        wg:       sync.WaitGroup{},
    }
}

// Add 添加
func (ap *WaitGroup) Add(num int) {
    for i := 0; i < num; i++ {
        ap.workChan <- i
        ap.wg.Add(1)
    }
}

// Done 完结
func (ap *WaitGroup) Done() {
LOOP:
    for {
        select {
        case <-ap.workChan:
            break LOOP
        }
    }
    ap.wg.Done()
}

// Wait 等待
func (ap *WaitGroup) Wait() {
    ap.wg.Wait()
}

test:

package pool

import (
    "fmt"
    "testing"
    "time"
)

func TestRun(t *testing.T) {
    work := NewPool(4)

    for i := 0; i < 50; i++ {
        work.Add(1)
        go testFunc(i, work)
    }

    fmt.Println("waiting...")
    work.Wait()
    t.Log("done")
}

func testFunc(i int, wg *WaitGroup) {
    defer wg.Done()
    fmt.Println(time.Now().Format("2006-01-02T15:04:05Z07:00"), "output: ", i)
    time.Sleep(time.Second * 1)
    fmt.Println(time.Now().Format("2006-01-02T15:04:05Z07:00"), "output: ", i, "done")
}

输出:

2018-12-04T14:22:27+08:00 output:  3
2018-12-04T14:22:27+08:00 output:  1
2018-12-04T14:22:27+08:00 output:  0
2018-12-04T14:22:27+08:00 output:  2
2018-12-04T14:22:28+08:00 output:  3 done
2018-12-04T14:22:28+08:00 output:  0 done
2018-12-04T14:22:28+08:00 output:  1 done
2018-12-04T14:22:28+08:00 output:  5
2018-12-04T14:22:28+08:00 output:  6
2018-12-04T14:22:28+08:00 output:  2 done
2018-12-04T14:22:28+08:00 output:  7
2018-12-04T14:22:28+08:00 output:  4
2018-12-04T14:22:29+08:00 output:  4 done
2018-12-04T14:22:29+08:00 output:  8
2018-12-04T14:22:29+08:00 output:  7 done
2018-12-04T14:22:29+08:00 output:  6 done
.....

这里还是要带上 sync.WaitGroup, 保证最后一次循环时携程不会过早退出

你可能感兴趣的:(后端,golang)