• 最近使用 Golang 写一个并发执行的测试脚本
  • 之前习惯使用 Java,习惯性想先建一个线程池。然后意识到 Golang 没有封装好的线程池
  • 结合之前学习的 Goroutine 原理和 Golang 大道至简的设计思想,可能 Goroutine 的开销和切换代价比较低,不需要对并发数有过多限制
  • 但是 Goroutine 启动数量过多的话总感觉不太好,于是利用锁和通道实现了简单的线程池做并发控制,欢迎大家点评
  • 源码地址:https://github.com/wangao1236/GoPool

1. 相关接口

  • 接口仿照 Java 的 ExecutorService 和 Runnable 接口定义:
// Task represents an in-process Goroutine task.
type Task interface {
    // Run method corresponds to Run method of Java's Runnable interface.
    Run()
}

// Executor defines the actions associated with the Goroutine pool.
type Executor interface {
    // Execute method corresponds to Execute method of Java's ExecutorService interface.
    Execute(task Task)
    // Wait waits for all the tasks to complete.
    Wait()
    // Done returns a channel which is closed if all the tasks completed.
    Done() chan struct{}
}
View Code

相关文章: