• 0
  • 0
分享

对于性能测试来讲,使用编程语言实现性能测试用例的核心就是并发编程,也就是同时执行多个测试用例,以模拟真实的负载情况。并发编程可以有效地提高测试效率,可以更快地发现系统中的瓶颈和性能问题。在实现并发编程时,需要考虑线程的同步和互斥,以确保测试结果的正确性和可靠性。此外,还需要考虑如何分配和管理资源,以避免资源竞争和浪费。

之前已经使用了Java实现,最近在计划使用Go语言实现一些新的压测功能的开发,这其中肯定也少不了使用到线程池(Go中协程池)。虽然Go语言协程已经非常强大了,很多情况下,我们可以直接使用go关键字直接创建协程去执行任务。但是在任务调度和负载保护的场景中,还是有所欠缺。所以在参考了Java线程池实现类java.util.concurrent.ThreadPoolExecutor自己实现了一个包含等待队列、调度以及等待队列任务完成的协程池。

PS:文中若在Go语言语境中出现线程,均指协程。

ThreadPoolExecutor分析

首先我们看看java.util.concurrent.ThreadPoolExecutor的实现中几个比较重要的功能点,然后简单介绍实现逻辑。下面是构造方法:

/**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @param threadFactory the factory to use when the executor
     *        creates a new thread
     * @param handler the handler to use when execution is blocked
     *        because the thread bounds and queue capacities are reached
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue}
     *         or {@code threadFactory} or {@code handler} is null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
    }

这里我省略了具体实现,我们看到参数:

  • 核心线程数、最大线程数,这两个用来管理线程池的数量。
  • 最大空闲时间,时间单位,这俩组合起来回收空闲线程。
  • workQueue,用例暂存任务
  • 线程工厂和拒绝策略,这俩用处少,忽略。(Go协程池也没有设计这俩) 下面就要祭出个人原创画作:

这里我借鉴了 动态修改coreThread线程池拓展的思路,不再依靠任务队列是否已满来作为增加线程池线程数的依据。除了依赖等待队列的数量以外,还提供单独的API(这一点跟java.util.concurrent.ThreadPoolExecutor是一样的)。

协程池属性设计

我从Java抄来两个属性:核心数,最大数。其中核心数在协程池自己管理中收到最大值的限制,在使用API时不受限制。

同样的,我抄来一个等待队列的概念,使用chan func() taskType实现,taskType用来区分是普通任务还是具有管理效果的任务(目前只有减少协程数管理事件,自增事件通过单独的协程实现)

超时时间,这个必不可少,庆幸的是Go在这方面比较灵活,我抄了一个简单Demo实现。

我增加了活跃协程数(这个在java.util.concurrent.ThreadPoolExecutor也有,但未显式展示),协程池状态(防止main结束导致进程直接结束)。

计数类,收到任务数,执行任务数,用来统计任务执行数量。这个同java.util.concurrent.ThreadPoolExecutor。

协程池实现

struct展示

type GorotinesPool struct {
 Max          int
 Min          int
 tasks        chan func() taskType
 status       bool
 active       int32
 ReceiveTotal int32
 ExecuteTotal int32
 addTimeout   time.Duration
}

事件类型枚举

type taskType int

const (
 normal taskType = 0
 reduce taskType = 1
)

构造方法

这里我选择了直接创建所有核心线程数。

  • 如果复用java.util.concurrent.ThreadPoolExecutor后创建,会功能变得复杂
  • Go语言创建协程资源消耗较低
  • 测试下来,耗时非常低,简单粗暴但是可靠
  • // GetPool

  • //  @Description: 创建线程池

  • //  @param max 最大协程数

  • //  @param min 最小协程数

  • //  @param maxWaitTask 最大任务等待长度

  • //  @param timeout 添加任务超时时间,单位s

  • //  @return *GorotinesPool

  • //

  • func GetPool(max, min, maxWaitTask, timeout int) *GorotinesPool {

  •  p := &GorotinesPool{

  •   Max:          max,

  •   Min:          min,

  •   tasks:        make(chan func() taskType, maxWaitTask),

  •   status:       true,

  •   active:       0,

  •   ReceiveTotal: 0,

  •   ExecuteTotal: 0,

  •   addTimeout:   time.Duration(timeout) * time.Second,

  •  }

  •  for i := 0; i < min; i++ {

  •   atomic.AddInt32(&p.active, 1)

  •   go p.worker()

  •  }

  •  go func() {

  •   for {

  •    if !p.status {

  •     break

  •    }

  •    ftool.Sleep(1000)

  •    p.balance()

  •   }

  •  }()

  •  return p

  • }


管理协程数

主要分成2个:增加和减少,增加比较简单,减少的话,我通过管理事件(taskType)实现,如果需要减少线程数,我就往队列里面添加一个reduce的事件,然后任意一个协程收到之后就终止。后面会分享worker实现。

// AddWorker
//  @Description: 添加worker,协程数加1
//  @receiver pool
//
func (pool *GorotinesPool) AddWorker() {
 atomic.AddInt32(&pool.active, 1)
 go pool.worker()
}

// ReduceWorker
//  @Description: 减少worker,协程数减1
//  @receiver pool
//
func (pool *GorotinesPool) ReduceWorker() {
 atomic.AddInt32(&pool.active, -1)
 pool.tasks <- func() taskType {
  return reduce
 }
}

// balance
//  @Description: 平衡活跃协程数
//  @receiver pool
//
func (pool *GorotinesPool) balance() {
 if pool.status {
  if len(pool.tasks) > 0 && pool.active < int32(pool.Max) {
   pool.AddWorker()
  }
  if len(pool.tasks) == 0 && pool.active > int32(pool.Min) {
   pool.ReduceWorker()
  }
 }
}

worker

// worker
//  @Description: 开始执行协程
//  @receiver pool
//
func (pool *GorotinesPool) worker() {
 defer func() {
  if p := recover(); p != nil {
   log.Printf("execute task fail: %v", p)
  }
 }()
Fun:
 for t := range pool.tasks {
  atomic.AddInt32(&pool.ExecuteTotal, 1)
  switch t() {
  case normal:
   atomic.AddInt32(&pool.active, -1)
  case reduce:
   if pool.active > int32(pool.Min) {
    break Fun
   }
  }
 }
}

保障任务完成

为了防止进程终止而任务没有完成,我增加了线程池的状态state和等待方法(此方法需要显式调用)。

// Wait
//  @Description: 结束等待任务完成
//  @receiver pool
//
func (pool *GorotinesPool) Wait() {
 pool.status = false
Fun:
 for {
  if len(pool.tasks) == 0 || pool.active == 0 {
   break Fun
  }
  ftool.Sleep(1000)
 }
 defer close(pool.tasks)
 log.Printf("recieve: %d,execute: %d", pool.ReceiveTotal, pool.ExecuteTotal)
}

执行任务

有了以上的基础,执行就比较简单了。

// Execute
//  @Description: 执行任务
//  @receiver pool
//  @param t
//  @return error
//
func (pool *GorotinesPool) Execute(t func()) error {
 if pool.status {
  select {
  case pool.tasks <- func() taskType {
   t()
   return normal
  }:
   atomic.AddInt32(&pool.ReceiveTotal, 1)
   return nil
  case <-time.After(pool.addTimeout):
   return errors.New("add tasks timeout")
  }
 } else {
  return errors.New("pools is down")
 }
}

自测

自测用例

func TestPool(t *testing.T) {
 pool := execute.GetPool(1000, 1, 200, 1)
 for i := 0; i < 3; i++ {
  pool.Execute(func() {
   log.Println(i)
   ftool.Sleep(1000)
  })
 }
 ftool.Sleep(3000)
 pool.Wait()
 log.Printf("T : %d", pool.ExecuteTotal)
 log.Printf("R : %d", pool.ReceiveTotal)
 log.Printf("max : %d", pool.Max)
 log.Printf("min : %d", pool.Min)
}

下面是自测结果,从39s两个输出可以看出当时实际运行的协程数已经超过1了,协程池自增策略生效了。

2023/06/23 17:21:38 3
2023/06/23 17:21:39 3
2023/06/23 17:21:39 3
2023/06/23 17:21:41 recieve: 3,execute: 3
2023/06/23 17:21:41 T : 3
2023/06/23 17:21:41 R : 3
2023/06/23 17:21:41 max : 1000
2023/06/23 17:21:41 min : 1
--- PASS: TestPool (3.00s)

本次分享结束,协程池自测之后效果很不错,后面会依据这个协程池的设计进行其他性能测试功能开发。

FunTester原创专题推荐~

  • 900原创合集
  • 2021年原创合集
  • 2022年原创合集
  • 接口功能测试专题
  • 性能测试专题,
  • Groovy专题
  • Java、Groovy、Go、Python
  • 单测&白盒
  • FunTester社群风采
  • 测试理论鸡汤
  • FunTester视频专题
  • 案例分享:方案、BUG、爬虫
  • UI自动化专题
  • 测试工具专题
  • -- By FunTester


  • 【留下美好印记】
    赞赏支持
登录 后发表评论
+ 关注

热门文章

    最新讲堂

      • 推荐阅读
      • 换一换
          • 接着测试设计的思路来讲讲一、如何运用测试设计的方法   1、测试设计方法有很多,主要有以下几种:    2、不同阶段如何运用的测试设计方法   在项目或是产品的测试过程中,在不同的测试阶段,存在不同的测试方法。以开发阶段划分,测试过程可以分为单元测试、集成测试、系统测试和验收测试。Ø 单元测试     单元测试是对程序模块进行正确性的检验。如果单元测试目标是达到100%判定覆盖率,那测试设计方法就要采用判定逻辑的逻辑覆盖方法,通过分析和设计,达到...
            1 2 987
            分享
          • 摘要本文对自动化测试概念发展演变过程进行了简要概述,结合业界流行工具Selenium以实例进行描述,以期达到理论结合实际效果,同时也便于读者理解和应用。【关键词】Selenium WEB测试 自动化测试随着大数据时代到来客户需求变化导致软件开发模型多样化,巨大的数据量和重复性的输入输出工作给手工测试带来了极大的困扰,特别在产品版本升级的回归测试,耗费大量人力物力。在此背景下,自动化测试理念和实践应运而生。并形成了先进基础理论和框架和众多工具,极大提高了测试效率。自动脚本不仅可用于单元测试,还可用于集成测试,进而进行整体功能测试。1 自动化测试概念1.1 定义自动化测试是测试过程中仅需由测试者开...
            11 11 1133
            分享
          • 写在前面:这是我第一次参加实习面试,面试前也在网上查了一下算法岗面试的相关经验,受益颇大,因此自己面试完后也试着记录了一下,虽然没能通过最终面试,但也希望能给想面试相关岗位的人一些启发和帮助~关于面试准备:算法的技术面主要考察的是算法的灵活使用和现场编程能力,以及相关方向的模型(基本上就是统计机器学习、自然语言处理、计算机视觉这些),因此主要准备以下两个方面:经典的算法题目;复习各种常用的模型,特别简历写的项目中使用到的。一面:项目介绍和模型知识考察对简历上的一个项目进行介绍?(接下来是根据我项目和我说话中提到的模型,开始深入地追问)SVM模型的介绍LR模型的loss函数是啥?为什么选择它作为...
            0 0 1407
            分享
          • 1、如何提高selenium脚本的执行速度?Selenium脚本的执行速度受多方面因素的影响,如网速,操作步骤的繁琐程度,页面加载的速度,以及我们在脚本中设置的等待时间,运行脚本的线程数等。但是不能单方面追求运行速度的,要确保稳定性,能稳定地实现回归测试才是关键。我们可以从以下几个方面来提高速度:一、减少操作步骤,如经过三四步才能打开我们要测试的页面的话,我们就可以直接通过网址来打开,减少不必要的操作。二、中断页面加载,如果页面加载的内容过多,我们可以查看一下加载慢的原因,如果加载的内容不影响我们测试,就设置超时时间,中断页面加载。三、在设置等待时间的时候,可以sleep固定的时间,也可以检测...
            0 0 567
            分享
      • 51testing软件测试圈微信