├── AUTHORS ├── DESIGN.md ├── LICENSE ├── README.md ├── cpu-worker.go ├── docs ├── .DS_Store └── img │ ├── .DS_Store │ ├── big-picture.png │ ├── cpuworker.png │ ├── state-transition.png │ ├── step2-server-load.png │ ├── step3-server-load.png │ └── step4-server-load.png ├── example └── demo.go ├── go.mod └── priority-heap.go /AUTHORS: -------------------------------------------------------------------------------- 1 | # This is the official list of cpuworker authors for copyright purposes. 2 | 3 | # Please keep this list sorted with alphabetical order. 4 | 5 | Sen Han <00hnes@gmail.com> -------------------------------------------------------------------------------- /DESIGN.md: -------------------------------------------------------------------------------- 1 | ## CPU-Worker 是什么 2 | 3 | CPU-Worker是一个位于Golang Runtime之上的应用层goroutine调度器。 4 | 5 | ![](docs/img/cpuworker.png) 6 | 7 | 优点:完全处于应用层,可根据具体业务的特点定制调度策略;对Golang Runtime没有改动,能兼容所有大于等于 Golang 1.1 的版本(即需要runtime支持Work-Stealing)。 8 | 9 | ## 术语定义 10 | 11 | **Event Intensive Task**,顾名思义,事件密集型任务,其生命周期中的绝大部分时间都在等待event(可称之为off-cpu),只有极少部分时间在进行cpu运算。在Golang中,这些事件包括:被阻塞的i/o操作,被阻塞的channel读写,timer等待,mutex lock等等场景。 12 | 13 | 比如,下面这段代码就是典型的event intensive task: 14 | 15 | ```go 16 | func eiTask() { 17 | wCh := make(chan struct{}) 18 | go func() { 19 | time.Sleep(time.Millisecond) 20 | wCh <- struct{}{} 21 | }() 22 | <-wCh 23 | } 24 | ``` 25 | 26 | **CPU Intensive Task**,顾名思义,CPU密集型任务,其生命周期中的绝大部分甚至全部时间都在进行cpu运算(可称之为on-cpu),只有极少部分时间处于甚至从未处于过等待event的状态。 27 | 28 | 比如,下面这段代码就是典型的cpu intensive task: 29 | 30 | ```go 31 | func ck() uint32 { 32 | return crc32.ChecksumIEEE(make([]byte, 1024*512)) 33 | } 34 | ``` 35 | 36 | ## 问题描述 37 | 38 | Golang Runtime调度器的调度策略目前的实现为公平调度,但在实际应用场景中,不同类型的任务之间、甚至相同类型的任务之间都可能需要存在优先级关系。比如用Golang实现一个块存储引擎,那么一般情况下,相比于各类cpu任务,i/o任务应该拥有更高的优先级,因为在这种情况下,系统瓶颈更可能是在i/o而非cpu;再比如,我们用Golang实现一个网络服务,要求在高负载下能保证其中一些轻量CPU请求的延迟指标,但是在目前Golang Runtime的实现里,如果running & runnable goroutine中出现了一定数量的需要较长时间运行的cpu intensive task,那么必然会冲击到延迟指标。所以,我们需要一个能够根据应用特点自适应或者能够自由定制其具体调度策略的goroutine调度器。 39 | 40 | ![big-picture](docs/img/big-picture.png) 41 | 42 | 从另一个角度来说,我们将Kernel提供的线程模型和Golang提供的协程模型作对比,除了Golang协程比线程天生的低成本高并发优势之外,Kernel线程模型中一些十分有用的机制在Golang Runtime的协程模型中目前并不能找到与之对应的实现,比如[调度策略与优先级的动态修改](https://man7.org/linux/man-pages/man7/sched.7.html)。 43 | 44 | ## 实现原理 45 | 46 | 在阅读之前需要对GMP模型和Work-Stealing有一定的基础了解,除了阅读源码之外,推荐的资料如下: 47 | 48 | * [Go 语言设计与实现:调度器](https://draveness.me/golang/docs/part3-runtime/ch06-concurrency/golang-goroutine/) 49 | 50 | * [深入golang runtime的调度](https://zboya.github.io/post/go_scheduler/) 51 | 52 | ### 针对CPU密集型任务的基础调度思想 53 | 54 | 假设现在应用层只有两类Task,Event Intensive Task和CPU Intensive Task。 55 | 56 | 首先,Golang Runtime为我们提供了基础的公平调度和Work-Stealing等机制,但是它解决不了前面陈述的不同任务之间调度优先级的问题,我们可以在目前Golang Runtime所提供机制的基础上,在应用层我们自己管理自己的CPU Intensive Task,只要保证它们的并行度低于 *GOMAXPROCS*,这样就能保证Event Intensive Task一旦ready就会迅速地被consume 掉。 57 | 58 | 比如*GOMAXPROCS*当前值为6,并且当前的运行环境能提供这么多并行的线程资源,那么我们可以将任一时刻CPU Intensive Task的并行度控制在4个,那么剩余的两个P就自然会被runtime专门用来处理Event Intensive Task,这样就保证了Event Intensive Task的Latency。 59 | 60 | 为了解决某些CPU Intensive Task可能会运行很长时间的问题,我们可以引入时间片的概念,这样调度器就能做更精细的调度,比如针对不同任务的时间片动态划分和优先级策略调整等等。 61 | 62 | 代码和运行示例位于[此处](https://github.com/hnes/cpuworker/blob/main/README.md#test-result-on-aws)。 63 | 64 | 实现中,我们为每个Task传一个checkpoint函数入参,Task在执行过程中应该在不影响性能的前提下尽可能多的调用checkpoint函数,在此函数的执行过程中,如果发现cpuworker调度器发来了suspend信号,就将自己挂起直到收到resume信号继续运行。 65 | 66 | ### 推广到通用调度器 67 | 68 | 上面针对CPU密集型任务的基础调度器在理论上已经能够解决我们的问题,但是具体在使用时需要应用自己做好划分,可能会带来一定复杂度,尤其是对于那些已有一定量代码遗产并且可能大部分是类似 “CPU Intensive + Event Intensive” 这样类型耦合的代码而言,比如: 69 | 70 | ```go 71 | func hybridTask() { 72 | for{ 73 | wCh := make(chan struct{}) 74 | go func() { 75 | time.Sleep(time.Millisecond) 76 | wCh <- struct{}{} 77 | }() 78 | crc32.ChecksumIEEE(make([]byte, 1024*512)) 79 | <-wCh 80 | } 81 | } 82 | ``` 83 | 84 | 对于这些项目将CPU Intensive Task与Event Intensive Task解耦开可能会付出很大的成本,所以我们进一步提出并实现了一种更通用的应用层调度模型: 85 | 86 | ```go 87 | func hybridTask(eventCallFp func(func())) { 88 | for{ 89 | // nonblock 90 | wCh := make(chan struct{}) 91 | // nonblock goroutine spawning 92 | go func() { 93 | // another event intensive goroutine 94 | time.Sleep(time.Millisecond) 95 | wCh <- struct{}{} 96 | }() 97 | // nonblock 98 | crc32.ChecksumIEEE(make([]byte, 1024*512)) 99 | // event operation 100 | eventCallFp(func(){ 101 | <-wCh 102 | }) 103 | } 104 | } 105 | ``` 106 | 107 | 此处的eventCallFp与之前的checkpointFp类似,唯一不同的是,eventCallFp会有一个函数入参,当此入参非nil时,它需要是一个Event Intensive Task。 108 | 109 | eventCallFp的执行流程是,首先判断入参是否为nil,若入参为nil,等价于调用checkpointFp,否则:立即将P还给cpuworker调度器,然后执行入参中的Event Intensive Task,执行完毕之后将自己放到cpuworker调度器的runnable task queue里面,在保证每个Task不会被饿死的前提下,cpuworker调度器会根据每个Task的运行特征给每个Task计算一个动态的优先级分数,尽可能保证CPU用时短小的、很像Event Intensive Task的Task得到优先调度权。 110 | 111 | 核心思想是,如果一个Task的on-cpu时间越短、off-cpu时间越长,那么它的优先级就应该越高。 112 | 113 | 一个Task的生命周期中可能的阶段如下: 114 | 115 | ![state-transition](docs/img/state-transition.png) 116 | 117 | ① 新创建的Task第一次被调度运行 118 | 119 | ② Task在执行checkpointFp检查时发现已经收到了调度器的挂起指令,于是将自己放到runnable task queue里,阻塞等待恢复运行信号 120 | 121 | ③ 挂起中的Task收到了调度器发来的恢复运行信号,继续运行 122 | 123 | ④ Task先将P还给cpuworker调度器,然后执行Event Intensive Task 124 | 125 | ⑤ 完成Event Intensive Task的执行,Task将自己放到runnable task queue里,等待被恢复运行 126 | 127 | ⑥ Task结束运行 128 | 129 | 自此,cpuworker的协程模型和内核提供的线程模型除了cpuworker需要协作抢占之外完全相同。所以,关于调度器的设计可以适当参考内核线程调度器的调度算法,另外,因为cpuworker是处于用户空间的,可以方便地做更多针对业务特性的定制与优化,而不仅仅必须是一个通用型的调度器,因为“通用”必然在会在某种应用场景下表现不良。 130 | 131 | 一些关于内核线程调度算法的参考资料如下: 132 | 133 | * [CFS Scheduler](https://www.kernel.org/doc/html/latest/scheduler/sched-design-CFS.html) 134 | * [Linux Kernel调度器的过去,现在和未来](https://my.oschina.net/u/4585157/blog/4672238) 135 | * [从几个问题开始理解CFS调度器](http://linuxperf.com/?p=42) 136 | * [Linux内核CFS调度器的实现](https://blog.eastonman.com/blog/2021/02/cfs/) 137 | 138 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 The cpuworker Authors 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cpuworker 2 | 3 | ## Status 4 | 5 | Working in process. 6 | 7 | ## Proposal For Go 8 | 9 | [proposal: runtime/scheduler: it is time to bring Go a better scheduler maybe like Linux Kernel's CFS](https://github.com/golang/go/issues/51071) 10 | 11 | ## Run the Demo 12 | 13 | Make sure the GOMAXPROCS is bigger than 1 and there is at least `GOMAXPROCS` physical OS threads available. 14 | 15 | Run the [example/demo.go](example/demo.go). 16 | 17 | ```bash 18 | # feel free to tune the parameters below if you like 19 | 20 | # cmd 1 21 | while true; do sleep 1;ab -s10000000 -c 10 -n 60 http://127.0.0.1:8080/delay1ms; done 22 | 23 | # cmd 2 24 | while true; do sleep 1;ab -s10000000 -c 10 -n 60 http://127.0.0.1:8080/checksumWithoutCpuWorker; done 25 | 26 | # cmd 3 27 | while true; do sleep 1;ab -s10000000 -c 10 -n 60 http://127.0.0.1:8080/checksumWithCpuWorker; done 28 | 29 | # cmd 4 30 | while true; do sleep 1;ab -s10000000 -c 10 -n 60 http://127.0.0.1:8080/checksumSmallTaskWithCpuWorker; done 31 | ``` 32 | 33 | Step 1: Killall already existing cmd `x`, then run the cmd 1. 34 | 35 | Step 2: Killall already existing cmd `x`, then run the cmd 1 and cmd 2 simultaneously. 36 | 37 | Step 3: Killall already existing cmd `x`, then run the cmd 1 and cmd 3 simultaneously. 38 | 39 | Step 4: Killall already existing cmd `x`, then run the cmd 1, cmd 3 and cmd 4 simultaneously. 40 | 41 | Please watch the latency which cmd 1 and cmd 4 yields carefully at every step and then you would catch the difference :-D 42 | 43 | ## Test Result On AWS 44 | 45 | The server [example/demo.go](example/demo.go) is running at an aws instance `c5d.12xlarge` and with the env `GOMAXPROCS` set to 16. 46 | 47 | ```bash 48 | $ GOMAXPROCS=16 ./cpuworker-demo 49 | 50 | GOMAXPROCS: 16 cpuWorkerMaxP: 12 length of crc32 bs: 262144 51 | ``` 52 | 53 | The benchmark tool is running at an aws instance `c5d.4xlarge`. The two machine is running at a same cluster placement group. 54 | 55 | ```bash 56 | # please complete the server IP 57 | SeverIP=x.x.x.x 58 | 59 | # cmd 1 60 | while true; do sleep 1;ab -s10000000 -c 100 -n 60000 http://$SeverIP:8080/delay1ms; done 61 | 62 | # cmd 2 63 | while true; do sleep 1;ab -s10000000 -c 100 -n 10000 http://$SeverIP:8080/checksumWithoutCpuWorker; done 64 | 65 | # cmd 3 66 | while true; do sleep 1;ab -s10000000 -c 100 -n 10000 http://$SeverIP:8080/checksumWithCpuWorker; done 67 | 68 | # cmd 4 69 | while true; do sleep 1;ab -s10000000 -c 100 -n 10000 http://$SeverIP:8080/checksumSmallTaskWithCpuWorker; done 70 | ``` 71 | 72 | Step 1: Killall already existing cmd `x`, then run the cmd 1 (run the standalone benchmark of delay1ms). 73 | 74 | ```bash 75 | $ ab -s10000000 -c 100 -n 60000 http://$SeverIP:8080/delay1ms 76 | This is ApacheBench, Version 2.3 <$Revision: 1879490 $> 77 | Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ 78 | Licensed to The Apache Software Foundation, http://www.apache.org/ 79 | 80 | Benchmarking 172.31.47.63 (be patient) 81 | Completed 1000 requests 82 | Completed 2000 requests 83 | Completed 3000 requests 84 | Completed 4000 requests 85 | Completed 5000 requests 86 | Completed 6000 requests 87 | Completed 7000 requests 88 | Completed 8000 requests 89 | Completed 9000 requests 90 | Completed 10000 requests 91 | Finished 10000 requests 92 | 93 | Server Software: 94 | Server Hostname: 172.31.47.63 95 | Server Port: 8080 96 | 97 | Document Path: /delay1ms 98 | Document Length: 37 bytes 99 | 100 | Concurrency Level: 100 101 | Time taken for tests: 0.225 seconds 102 | Complete requests: 10000 103 | Failed requests: 1066 104 | (Connect: 0, Receive: 0, Length: 1066, Exceptions: 0) 105 | Total transferred: 1538813 bytes 106 | HTML transferred: 368813 bytes 107 | Requests per second: 44413.06 [#/sec] (mean) 108 | Time per request: 2.252 [ms] (mean) 109 | Time per request: 0.023 [ms] (mean, across all concurrent requests) 110 | Transfer rate: 6674.16 [Kbytes/sec] received 111 | 112 | Connection Times (ms) 113 | min mean[+/-sd] median max 114 | Connect: 0 0 0.2 0 1 115 | Processing: 1 2 0.4 2 4 116 | Waiting: 1 2 0.4 1 4 117 | Total: 1 2 0.5 2 5 118 | ERROR: The median and mean for the waiting time are more than twice the standard 119 | deviation apart. These results are NOT reliable. 120 | 121 | Percentage of the requests served within a certain time (ms) 122 | 50% 2 123 | 66% 2 124 | 75% 2 125 | 80% 2 126 | 90% 3 127 | 95% 3 128 | 98% 4 129 | 99% 4 130 | 100% 5 (longest request) 131 | ``` 132 | 133 | Step 2: Killall already existing cmd `x`, then run the cmd 1 and cmd 2 simultaneously (run the benchmark of delay1ms with a very heavy cpu load without cpuworker). 134 | 135 | Curent CPU load of the server side (and please note that the load average is already reaching the `GOMAXPROCS`, i.e. 16 in this case): 136 | 137 | ![step2-server-load](docs/img/step2-server-load.png) 138 | 139 | ```bash 140 | $ ab -s10000000 -c 100 -n 60000 http://$SeverIP:8080/delay1ms 141 | This is ApacheBench, Version 2.3 <$Revision: 1879490 $> 142 | Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ 143 | Licensed to The Apache Software Foundation, http://www.apache.org/ 144 | 145 | Benchmarking 172.31.47.63 (be patient) 146 | Completed 1000 requests 147 | Completed 2000 requests 148 | Completed 3000 requests 149 | Completed 4000 requests 150 | Completed 5000 requests 151 | Completed 6000 requests 152 | Completed 7000 requests 153 | Completed 8000 requests 154 | Completed 9000 requests 155 | Completed 10000 requests 156 | Finished 10000 requests 157 | 158 | Server Software: 159 | Server Hostname: 172.31.47.63 160 | Server Port: 8080 161 | 162 | Document Path: /delay1ms 163 | Document Length: 38 bytes 164 | 165 | Concurrency Level: 100 166 | Time taken for tests: 31.565 seconds 167 | Complete requests: 10000 168 | Failed requests: 5266 169 | (Connect: 0, Receive: 0, Length: 5266, Exceptions: 0) 170 | Total transferred: 1553977 bytes 171 | HTML transferred: 383977 bytes 172 | Requests per second: 316.80 [#/sec] (mean) 173 | Time per request: 315.654 [ms] (mean) 174 | Time per request: 3.157 [ms] (mean, across all concurrent requests) 175 | Transfer rate: 48.08 [Kbytes/sec] received 176 | 177 | Connection Times (ms) 178 | min mean[+/-sd] median max 179 | Connect: 0 0 0.1 0 1 180 | Processing: 50 314 99.3 293 1038 181 | Waiting: 11 305 102.5 292 1038 182 | Total: 50 314 99.3 293 1038 183 | 184 | Percentage of the requests served within a certain time (ms) 185 | 50% 293 186 | 66% 323 187 | 75% 353 188 | 80% 380 189 | 90% 454 190 | 95% 504 191 | 98% 604 192 | 99% 615 193 | 100% 1038 (longest request) 194 | ``` 195 | 196 | Step 3: Killall already existing cmd `x`, then run the cmd 1 and cmd 3 simultaneously (run the benchmark of delay1ms with a very heavy cpu load with cpuworker). 197 | 198 | Curent CPU load of the server side (and please note that the load average is near the `cpuWorkerMaxP`, i.e. 12 in this case, and you could set this parameter by yourself): 199 | 200 | ![step3-server-load](docs/img/step3-server-load.png) 201 | 202 | ```bash 203 | $ ab -s10000000 -c 100 -n 60000 http://$SeverIP:8080/delay1ms 204 | This is ApacheBench, Version 2.3 <$Revision: 1879490 $> 205 | Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ 206 | Licensed to The Apache Software Foundation, http://www.apache.org/ 207 | 208 | Benchmarking 172.31.47.63 (be patient) 209 | Completed 1000 requests 210 | Completed 2000 requests 211 | Completed 3000 requests 212 | Completed 4000 requests 213 | Completed 5000 requests 214 | Completed 6000 requests 215 | Completed 7000 requests 216 | Completed 8000 requests 217 | Completed 9000 requests 218 | Completed 10000 requests 219 | Finished 10000 requests 220 | 221 | 222 | Server Software: 223 | Server Hostname: 172.31.47.63 224 | Server Port: 8080 225 | 226 | Document Path: /delay1ms 227 | Document Length: 37 bytes 228 | 229 | Concurrency Level: 100 230 | Time taken for tests: 0.234 seconds 231 | Complete requests: 10000 232 | Failed requests: 1005 233 | (Connect: 0, Receive: 0, Length: 1005, Exceptions: 0) 234 | Total transferred: 1538877 bytes 235 | HTML transferred: 368877 bytes 236 | Requests per second: 42655.75 [#/sec] (mean) 237 | Time per request: 2.344 [ms] (mean) 238 | Time per request: 0.023 [ms] (mean, across all concurrent requests) 239 | Transfer rate: 6410.35 [Kbytes/sec] received 240 | 241 | Connection Times (ms) 242 | min mean[+/-sd] median max 243 | Connect: 0 0 0.2 0 1 244 | Processing: 1 2 0.5 2 4 245 | Waiting: 1 2 0.4 2 4 246 | Total: 1 2 0.5 2 5 247 | 248 | Percentage of the requests served within a certain time (ms) 249 | 50% 2 250 | 66% 2 251 | 75% 2 252 | 80% 3 253 | 90% 3 254 | 95% 4 255 | 98% 4 256 | 99% 4 257 | 100% 5 (longest request) 258 | ``` 259 | 260 | Step 4: Killall already existing cmd `x`, then run the cmd 1, cmd 3 and cmd 4 simultaneously (run the benchmark of delay1ms and checksumSmallTaskWithCpuWorker with a very heavy cpu load with cpuworker). 261 | 262 | Curent CPU load of the server side (and please note that the load average is near the `cpuWorkerMaxP`, i.e. 12 in this case, and you could set this parameter by yourself): 263 | 264 | ![step4-server-load](docs/img/step4-server-load.png) 265 | 266 | ```bash 267 | $ ab -s10000000 -c 100 -n 60000 http://$SeverIP:8080/delay1ms 268 | 269 | This is ApacheBench, Version 2.3 <$Revision: 1879490 $> 270 | Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ 271 | Licensed to The Apache Software Foundation, http://www.apache.org/ 272 | 273 | Benchmarking 172.31.47.63 (be patient) 274 | Completed 1000 requests 275 | Completed 2000 requests 276 | Completed 3000 requests 277 | Completed 4000 requests 278 | Completed 5000 requests 279 | Completed 6000 requests 280 | Completed 7000 requests 281 | Completed 8000 requests 282 | Completed 9000 requests 283 | Completed 10000 requests 284 | Finished 10000 requests 285 | 286 | 287 | Server Software: 288 | Server Hostname: 172.31.47.63 289 | Server Port: 8080 290 | 291 | Document Path: /delay1ms 292 | Document Length: 37 bytes 293 | 294 | Concurrency Level: 100 295 | Time taken for tests: 0.238 seconds 296 | Complete requests: 10000 297 | Failed requests: 1038 298 | (Connect: 0, Receive: 0, Length: 1038, Exceptions: 0) 299 | Total transferred: 1538857 bytes 300 | HTML transferred: 368857 bytes 301 | Requests per second: 42031.11 [#/sec] (mean) 302 | Time per request: 2.379 [ms] (mean) 303 | Time per request: 0.024 [ms] (mean, across all concurrent requests) 304 | Transfer rate: 6316.39 [Kbytes/sec] received 305 | 306 | Connection Times (ms) 307 | min mean[+/-sd] median max 308 | Connect: 0 0 0.2 0 1 309 | Processing: 1 2 0.5 2 5 310 | Waiting: 1 2 0.4 1 5 311 | Total: 1 2 0.6 2 5 312 | ERROR: The median and mean for the waiting time are more than twice the standard 313 | deviation apart. These results are NOT reliable. 314 | 315 | Percentage of the requests served within a certain time (ms) 316 | 50% 2 317 | 66% 2 318 | 75% 2 319 | 80% 3 320 | 90% 3 321 | 95% 4 322 | 98% 4 323 | 99% 4 324 | 100% 5 (longest request) 325 | 326 | $ ab -s10000000 -c 100 -n 10000 http://$SeverIP:8080/checksumSmallTaskWithCpuWorker 327 | 328 | This is ApacheBench, Version 2.3 <$Revision: 1879490 $> 329 | Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ 330 | Licensed to The Apache Software Foundation, http://www.apache.org/ 331 | 332 | Benchmarking 172.31.47.63 (be patient) 333 | Completed 1000 requests 334 | Completed 2000 requests 335 | Completed 3000 requests 336 | Completed 4000 requests 337 | Completed 5000 requests 338 | Completed 6000 requests 339 | Completed 7000 requests 340 | Completed 8000 requests 341 | Completed 9000 requests 342 | Completed 10000 requests 343 | Finished 10000 requests 344 | 345 | 346 | Server Software: 347 | Server Hostname: 172.31.47.63 348 | Server Port: 8080 349 | 350 | Document Path: /checksumSmallTaskWithCpuWorker 351 | Document Length: 71 bytes 352 | 353 | Concurrency Level: 100 354 | Time taken for tests: 0.469 seconds 355 | Complete requests: 10000 356 | Failed requests: 9157 357 | (Connect: 0, Receive: 0, Length: 9157, Exceptions: 0) 358 | Total transferred: 1889624 bytes 359 | HTML transferred: 719624 bytes 360 | Requests per second: 21333.56 [#/sec] (mean) 361 | Time per request: 4.687 [ms] (mean) 362 | Time per request: 0.047 [ms] (mean, across all concurrent requests) 363 | Transfer rate: 3936.76 [Kbytes/sec] received 364 | 365 | Connection Times (ms) 366 | min mean[+/-sd] median max 367 | Connect: 0 0 0.3 0 2 368 | Processing: 1 4 3.3 3 13 369 | Waiting: 1 4 3.3 3 13 370 | Total: 2 5 3.4 3 13 371 | 372 | Percentage of the requests served within a certain time (ms) 373 | 50% 3 374 | 66% 4 375 | 75% 6 376 | 80% 9 377 | 90% 11 378 | 95% 11 379 | 98% 12 380 | 99% 12 381 | 100% 13 (longest request) 382 | ``` 383 | 384 | At step 4, the latency of `checksumSmallTaskWithCpuWorker` is around 10ms, that is because: 385 | 386 | - the DefaultMaxTimeSlice of cpuworker is 10ms (feel free to tune it if you like) 387 | - cpuworker's scheduler thinks the new task always has a higher priority than current running and suspended tasks, so if the running tasks reach its MaxTimeSlice limit, the scheduler will suspend it at checkpoint and let the new task to run as soon as possible 388 | 389 | ## Contributing 390 | 391 | Welcome to contribute 🎉🎉🎉 392 | 393 | Before your pull request is merged, you must sign the [Developer Certificate of Origin](https://developercertificate.org/). Please visit the [DCO](https://github.com/apps/dco) for more information. Basically you add the `Signed-off-by: Real Name ` inside the commit message to claim all your contribution adheres the requirements inside the [DCO](https://github.com/apps/dco). 394 | 395 | ## Copyright and License 396 | 397 | Copyright (C) 2021, by the cpuworker Authors 398 | 399 | Unless otherwise noted, the cpuworker source files are distributed under the Apache License Version 2.0. See the [LICENSE](LICENSE) file for details. 400 | -------------------------------------------------------------------------------- /cpu-worker.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The cpuworker Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package cpuworker 16 | 17 | import ( 18 | "runtime" 19 | "sync" 20 | "sync/atomic" 21 | "time" 22 | ) 23 | 24 | var glWorkers *Workers 25 | var glWorkersLock sync.Mutex 26 | 27 | var traceFlag = true 28 | 29 | // duration between (task repay p to scheduler, scheduler rcv this p ) 30 | var traceMaxPdelay = time.Duration(0) 31 | 32 | const DefaultMaxTimeSlice = time.Microsecond * 1000 33 | const MaxEITaskTimeslice = time.Microsecond * 100 34 | const MaxNewTaskTimeslice = time.Microsecond * 200 35 | 36 | func init() { 37 | cpuP := CalcAutoP() 38 | workers := NewWorkers(cpuP, DefaultMaxTimeSlice) 39 | SetGlobalWorkers(workers) 40 | } 41 | 42 | const ( 43 | STAT_NEW = iota 44 | STAT_RUNNING 45 | STAT_SUSPENDED 46 | STAT_END 47 | ) 48 | 49 | type TaskHandle struct { 50 | // closed indicating the task is ended 51 | done chan struct{} 52 | // checkpoint 53 | // non-zero means should yield 54 | yieldFlag uint32 55 | // send one struct to this chan to tell manager current cpu worker is entering yield state 56 | yieldCh chan *P 57 | // receive one struct from this chan indicating current cpu worker should to be resumed 58 | resumeCh chan *P 59 | } 60 | 61 | func (h *TaskHandle) Sync() { 62 | <-h.done 63 | } 64 | 65 | type taskSchTiming struct { 66 | resumeCpuT time.Time 67 | suspendedCpuT time.Time 68 | enterEventCallT time.Time 69 | endEventCallT time.Time 70 | // event intensive factor 71 | eIfactor float32 72 | // sum and eiCt 73 | sumCpuDuration time.Duration 74 | sumEventCallDuration time.Duration 75 | eiCt uint64 76 | } 77 | 78 | var zeroT = time.Time{} 79 | 80 | func (t *Task) calcEventIntensiveScore() float32 { 81 | assert(false) 82 | return 0 83 | } 84 | 85 | type Task struct { 86 | validFlag bool 87 | // true: event intensive 88 | // false: cpu intensive 89 | eventIntensiveFlag bool 90 | // the bigger, the priority in scheduler would be higher 91 | eventIntensiveScore float32 92 | timing taskSchTiming 93 | 94 | stat int 95 | fp0 func() 96 | fp1 func(func()) 97 | fp2 func(func(func())) 98 | h TaskHandle 99 | // must > 0 100 | maxTimeSlice time.Duration 101 | // must > 0 102 | // keep const after initialized 103 | initMaxTimeSlice time.Duration 104 | p *P 105 | w *Workers 106 | // rcv p and resume runnable task 107 | pch chan *P 108 | } 109 | 110 | func (t *Task) assetValid() { 111 | assert(t.validFlag && t.w != nil) 112 | ct := 0 113 | if t.fp0 != nil { 114 | ct++ 115 | } 116 | if t.fp1 != nil { 117 | ct++ 118 | } 119 | if t.fp2 != nil { 120 | ct++ 121 | } 122 | assert(ct == 1) 123 | assert(t.stat == STAT_NEW || t.stat == STAT_RUNNING || 124 | t.stat == STAT_SUSPENDED || t.stat == STAT_END, 125 | ) 126 | } 127 | 128 | func (t *Task) timingStart(tm time.Time) { 129 | t.timing.resumeCpuT = zeroT 130 | t.timing.suspendedCpuT = zeroT 131 | t.timing.enterEventCallT = zeroT 132 | t.timing.endEventCallT = zeroT 133 | t.timing.eIfactor = 0 134 | t.timing.resumeCpuT = tm 135 | } 136 | 137 | func (t *Task) timingCk(tm time.Time) { 138 | t.timing.suspendedCpuT = tm 139 | } 140 | 141 | func (t *Task) timingEnterEventCall(tm time.Time) { 142 | t.timing.suspendedCpuT = tm 143 | t.timing.enterEventCallT = tm 144 | } 145 | 146 | func (t *Task) timingEndEventCall(tm time.Time) { 147 | t.timing.endEventCallT = tm 148 | } 149 | 150 | func (t *Task) timingEnd(tm time.Time) { 151 | t.timing.suspendedCpuT = tm 152 | } 153 | 154 | /* 155 | new ① ( 156 | (running ck ② runnable ① ) 157 | | 158 | (running ③ eventCall ④ runnable ① ) 159 | | 160 | (running ⑤ end) 161 | )* 162 | 163 | ① timingStart 164 | ② timingCk repayP calcEIfactorAndSumbitToRunnableTaskQueue 165 | ③ timingEnterEventCall repayP 166 | ④ timingEndEventCall calcEIfactorAndSumbitToRunnableTaskQueue 167 | ⑤ timingEnd repayP 168 | */ 169 | func (t *Task) calcEIfactorAndSumbitToRunnableTaskQueue() { 170 | isCk := false 171 | tm := &t.timing 172 | push := func() { 173 | cpuDur := tm.suspendedCpuT.Sub(tm.resumeCpuT) 174 | eiDur := tm.endEventCallT.Sub(tm.enterEventCallT) 175 | assert(cpuDur >= 0 && eiDur >= 0) 176 | tm.sumCpuDuration += cpuDur 177 | tm.sumEventCallDuration += eiDur 178 | assert(cpuDur >= 0 && eiDur >= 0 && tm.sumCpuDuration >= 0 && tm.sumEventCallDuration >= 0) 179 | } 180 | calcEiFactor := func() float32 { 181 | if tm.suspendedCpuT.Sub(tm.resumeCpuT) >= time.Millisecond { 182 | return 0 183 | } 184 | eiDdiv10 := tm.sumEventCallDuration >> 3 185 | var ret float32 186 | if tm.sumCpuDuration < time.Microsecond*10 { 187 | return 1.0 188 | } 189 | if tm.sumCpuDuration < eiDdiv10 { 190 | if tm.sumCpuDuration <= 0 { 191 | ret = float32(tm.sumEventCallDuration) / float32(1) 192 | } else { 193 | ret = float32(tm.sumEventCallDuration) / float32(tm.sumCpuDuration) 194 | } 195 | if tm.sumCpuDuration > time.Second { 196 | tm.sumCpuDuration = 0 197 | tm.sumEventCallDuration = 0 198 | } 199 | return ret 200 | } else { 201 | return 0 202 | } 203 | } 204 | if tm.enterEventCallT == zeroT && tm.endEventCallT == zeroT { 205 | isCk = true 206 | } 207 | push() 208 | var eIfactor float32 209 | if isCk { 210 | if tm.eiCt > 0 { 211 | eIfactor = calcEiFactor() 212 | } else { 213 | } 214 | } else { 215 | eIfactor = calcEiFactor() 216 | } 217 | 218 | if eiFactorBt0(eIfactor) { 219 | tm.eiCt += 1 220 | assert(tm.eiCt > 0) 221 | tm.eIfactor = eIfactor 222 | t.maxTimeSlice = t.initMaxTimeSlice 223 | t.w.runnableEventIntensiveTaskCh <- t 224 | } else { 225 | eIfactor = 0 226 | tm.eIfactor = eIfactor 227 | tm.eiCt = 0 228 | tm.sumCpuDuration = 0 229 | tm.sumEventCallDuration = 0 230 | t.maxTimeSlice = t.initMaxTimeSlice 231 | t.w.runnableCpuIntensiveTaskCh <- t 232 | } 233 | } 234 | 235 | // > 0 236 | func eiFactorBt0(factor float32) bool { 237 | if factor > 0.0001 { 238 | return true 239 | } else { 240 | return false 241 | } 242 | } 243 | 244 | func (t *Task) calcMaxTimeSlice() time.Duration { 245 | var smallest time.Duration 246 | if t.maxTimeSlice < t.initMaxTimeSlice { 247 | smallest = t.maxTimeSlice 248 | } else { 249 | smallest = t.initMaxTimeSlice 250 | } 251 | if smallest < t.w.maxTimeSlice { 252 | } else { 253 | smallest = t.w.maxTimeSlice 254 | } 255 | assert(smallest > 0) 256 | return smallest 257 | } 258 | 259 | // start running a newTask or a suspended task 260 | func (t *Task) resume(p *P, eiFlag bool, newFlag bool) { 261 | t.assetValid() 262 | p.assetValid() 263 | fixMaxTimeSlice := func() { 264 | if eiFlag { 265 | if t.initMaxTimeSlice > MaxEITaskTimeslice { 266 | if t.maxTimeSlice > MaxEITaskTimeslice { 267 | t.maxTimeSlice = MaxEITaskTimeslice 268 | } 269 | } 270 | } 271 | if newFlag { 272 | if t.initMaxTimeSlice > MaxNewTaskTimeslice { 273 | if t.maxTimeSlice > MaxNewTaskTimeslice { 274 | t.maxTimeSlice = MaxNewTaskTimeslice 275 | } 276 | } 277 | } 278 | } 279 | if t.stat == STAT_NEW { 280 | assert(t.p == nil) 281 | t.p = p 282 | finalFp := func() { 283 | fixMaxTimeSlice() 284 | t.timingStart(time.Now()) 285 | if t.fp1 != nil { 286 | t.fp1(func() { 287 | checkPoint(t) 288 | }) 289 | } else if t.fp0 != nil { 290 | t.fp0() 291 | } else { 292 | assert(t.fp2 != nil) 293 | t.fp2(func(ecfp func()) { 294 | if ecfp == nil { 295 | checkPoint(t) 296 | } else { 297 | eventRoutineCall(t, ecfp) 298 | } 299 | }) 300 | } 301 | t.p.assetValid() 302 | nowT := time.Now() 303 | if traceFlag { 304 | t.p.taskRepayPt = nowT 305 | } 306 | t.w.repayP(t.p) 307 | t.timingEnd(nowT) 308 | t.p = nil 309 | t.stat = STAT_END 310 | close(t.h.done) 311 | assert(len(t.pch) == 0) 312 | close(t.pch) 313 | } 314 | t.stat = STAT_RUNNING 315 | go finalFp() 316 | } else { 317 | assert(t.stat == STAT_SUSPENDED && t.p == nil) 318 | fixMaxTimeSlice() 319 | tryMustSndPch(t.pch, p) 320 | } 321 | } 322 | 323 | func checkPoint(t *Task) { 324 | yieldFlag := atomic.LoadUint32(&t.h.yieldFlag) 325 | if yieldFlag != 0 { 326 | // should yield 327 | assert(t.p != nil && t.stat == STAT_RUNNING) 328 | p := t.p 329 | t.p = nil 330 | t.stat = STAT_SUSPENDED 331 | nowT := time.Now() 332 | t.timingCk(nowT) 333 | if traceFlag { 334 | p.taskRepayPt = nowT 335 | } 336 | atomic.StoreUint32(&t.h.yieldFlag, 0) 337 | tryMustSndPch(t.w.availablePchan, p) 338 | t.calcEIfactorAndSumbitToRunnableTaskQueue() 339 | // block at here untill scheduler wants us to resume 340 | var ok bool 341 | t.p, ok = <-t.pch 342 | assert(ok) 343 | t.p.assetValid() 344 | t.stat = STAT_RUNNING 345 | t.timingStart(time.Now()) 346 | } 347 | } 348 | 349 | func eventRoutineCall(t *Task, eventRoutineFp func()) { 350 | nowT := time.Now() 351 | t.timingEnterEventCall(nowT) 352 | assert(t.p != nil && t.stat == STAT_RUNNING) 353 | p := t.p 354 | t.p = nil 355 | assert(p.eventCallTask == nil) 356 | p.eventCallTask = t 357 | t.stat = STAT_SUSPENDED 358 | if traceFlag { 359 | p.taskRepayPt = nowT 360 | } 361 | tryMustSndPch(t.w.availablePchan, p) 362 | { 363 | eventRoutineFp() 364 | } 365 | t.timingEndEventCall(time.Now()) 366 | t.calcEIfactorAndSumbitToRunnableTaskQueue() 367 | // block at here until scheduler wants us to resume 368 | var ok bool 369 | t.p, ok = <-t.pch 370 | assert(ok) 371 | t.p.assetValid() 372 | t.stat = STAT_RUNNING 373 | t.timingStart(time.Now()) 374 | } 375 | 376 | func (t *Task) sendSuspendSignal() { 377 | atomic.CompareAndSwapUint32(&t.h.yieldFlag, 0, 1) 378 | } 379 | 380 | func tryMustRcvPch(pch chan *P) *P { 381 | select { 382 | case p := <-pch: 383 | return p 384 | default: 385 | assert(false) 386 | } 387 | assert(false) 388 | return nil 389 | } 390 | 391 | func tryMustSndPch(pch chan *P, p *P) { 392 | select { 393 | case pch <- p: 394 | return 395 | default: 396 | assert(false) 397 | } 398 | assert(false) 399 | } 400 | 401 | func (w *Workers) repayP(p *P) { 402 | p.assetValid() 403 | tryMustSndPch(w.availablePchan, p) 404 | } 405 | 406 | type P struct { 407 | validFlag bool 408 | idx int 409 | eventCallTask *Task 410 | taskRepayPt time.Time 411 | } 412 | 413 | func (p *P) assetValid() { 414 | assert(p.validFlag) 415 | } 416 | 417 | type taskSchUnit struct { 418 | validFlag bool 419 | resumeT time.Time 420 | taskPtr *Task 421 | } 422 | 423 | func (tu *taskSchUnit) assertValid() { 424 | assert(tu.validFlag && tu.taskPtr != nil) 425 | } 426 | 427 | type Workers struct { 428 | newTaskCh chan *Task 429 | runnableEventIntensiveTaskCh chan *Task 430 | runnableCpuIntensiveTaskCh chan *Task 431 | availablePchan chan *P 432 | // must > 0 433 | maxTimeSlice time.Duration 434 | // idx is the idx of P, and member is taskSchUnit 435 | taskSchArray []taskSchUnit 436 | exitCh chan struct{} 437 | } 438 | 439 | // if never timeout return (0, -1) 440 | // if there is a already timeout taskSchUnit return (0, validIdx) 441 | // otherwise normal return timeout > 0 and a valid idx 442 | func (w *Workers) calcDurationToNextTimeSliceTimeout() (timeout time.Duration, idx int) { 443 | var smallestSuspendT time.Time 444 | validUnitCt := 0 445 | for i, v := range w.taskSchArray { 446 | if v.validFlag { 447 | validUnitCt++ 448 | v.assertValid() 449 | } else { 450 | continue 451 | } 452 | maxTimeSlice := v.taskPtr.calcMaxTimeSlice() 453 | assert(validUnitCt > 0) 454 | if validUnitCt == 1 { 455 | smallestSuspendT = v.resumeT.Add(maxTimeSlice) 456 | idx = i 457 | } else { 458 | thisSuspendT := v.resumeT.Add(maxTimeSlice) 459 | if thisSuspendT.Before(smallestSuspendT) { 460 | smallestSuspendT = thisSuspendT 461 | idx = i 462 | } 463 | } 464 | } 465 | if validUnitCt > 0 { 466 | } else { 467 | return 0, -1 468 | } 469 | nowT := time.Now() 470 | w.taskSchArray[idx].assertValid() 471 | if smallestSuspendT.After(nowT) { 472 | return smallestSuspendT.Sub(nowT), idx 473 | } else { 474 | return 0, idx 475 | } 476 | } 477 | 478 | func NewWorkers(p int, maxTimeSlice time.Duration) *Workers { 479 | assert(p > 0) 480 | w := Workers{ 481 | newTaskCh: make(chan *Task, 1024*p), 482 | runnableEventIntensiveTaskCh: make(chan *Task, 1024*p), 483 | runnableCpuIntensiveTaskCh: make(chan *Task, 1024*p), 484 | availablePchan: make(chan *P, p), 485 | maxTimeSlice: maxTimeSlice, 486 | taskSchArray: make([]taskSchUnit, p), 487 | exitCh: make(chan struct{}), 488 | } 489 | for idx := range w.taskSchArray { 490 | w.availablePchan <- &P{ 491 | validFlag: true, 492 | idx: idx, 493 | } 494 | } 495 | go w.schedulerRoutine() 496 | return &w 497 | } 498 | 499 | func (w *Workers) schedulerRoutine() { 500 | closedCh := make(chan time.Time, 1) 501 | close(closedCh) 502 | var nilCh chan time.Time 503 | // eiT local buf 504 | var eiTask *Task 505 | eiTaskPq := newPrioTaskQueue() 506 | // local cpuT buf 507 | var cpuTask *Task 508 | // local newT buf 509 | var newTask *Task 510 | // local p buf 511 | var newp *P 512 | var pArray []*P 513 | tryToPushAllEiT := func() { 514 | if eiTask != nil { 515 | eiTaskPq.Push(eiTask, eiTask.timing.eIfactor) 516 | eiTask = nil 517 | } 518 | for { 519 | var eiT *Task 520 | select { 521 | case eiT = <-w.runnableEventIntensiveTaskCh: 522 | eiT.assetValid() 523 | default: 524 | } 525 | if eiT != nil { 526 | eiTaskPq.Push(eiT, eiT.timing.eIfactor) 527 | } else { 528 | break 529 | } 530 | } 531 | } 532 | // return (task, eiFlag, newFlag) 533 | mustGetTnb := func() (*Task, bool, bool) { 534 | // priority: 535 | // eIQ > newQ > cIQ 536 | tryToPushAllEiT() 537 | if eiTaskPq.Len() > 0 { 538 | return eiTaskPq.Pop().t, true, false 539 | } 540 | var ret *Task 541 | if newTask != nil { 542 | ret = newTask 543 | newTask = nil 544 | return ret, false, true 545 | } 546 | select { 547 | case ret = <-w.newTaskCh: 548 | return ret, false, true 549 | default: 550 | } 551 | if cpuTask != nil { 552 | ret = cpuTask 553 | cpuTask = nil 554 | return ret, false, false 555 | } 556 | // try to get one runnable task 557 | select { 558 | case ret = <-w.newTaskCh: 559 | return ret, false, true 560 | case ret = <-w.runnableCpuIntensiveTaskCh: 561 | return ret, false, false 562 | default: 563 | } 564 | panic("unexpected") 565 | } 566 | hasTask := func() bool { 567 | if eiTask != nil || newTask != nil || cpuTask != nil || 568 | eiTaskPq.Len() > 0 || len(w.newTaskCh) > 0 || 569 | len(w.runnableCpuIntensiveTaskCh) > 0 || 570 | len(w.runnableEventIntensiveTaskCh) > 0 { 571 | return true 572 | } else { 573 | return false 574 | } 575 | } 576 | pushNewP := func(newp *P) { 577 | assert(newp != nil) 578 | newp.assetValid() 579 | if traceFlag && newp.taskRepayPt != zeroT { 580 | d := time.Now().Sub(newp.taskRepayPt) 581 | if d > traceMaxPdelay { 582 | traceMaxPdelay = d 583 | } 584 | } 585 | tu := w.taskSchArray[newp.idx] 586 | if tu.validFlag { 587 | tu.assertValid() 588 | w.taskSchArray[newp.idx] = taskSchUnit{} 589 | } 590 | if newp.eventCallTask != nil { 591 | t := newp.eventCallTask 592 | if tu.validFlag { 593 | assert(tu.taskPtr == t) 594 | } 595 | newp.eventCallTask = nil 596 | } 597 | pArray = append(pArray, newp) 598 | newp = nil 599 | } 600 | tryToPushAllP := func() { 601 | if newp != nil { 602 | pushNewP(newp) 603 | newp = nil 604 | } 605 | for { 606 | var p *P 607 | select { 608 | case p = <-w.availablePchan: 609 | p.assetValid() 610 | default: 611 | } 612 | if p != nil { 613 | pushNewP(p) 614 | } else { 615 | break 616 | } 617 | } 618 | } 619 | mustGetPnb := func() *P { 620 | tryToPushAllP() 621 | assert(len(pArray) > 0) 622 | p := pArray[len(pArray)-1] 623 | pArray = pArray[0 : len(pArray)-1] 624 | return p 625 | } 626 | hasP := func() bool { 627 | return newp != nil || len(pArray) > 0 || len(w.availablePchan) > 0 628 | } 629 | 630 | for { 631 | assert(newp == nil) 632 | tryToPushAllP() 633 | if hasP() { 634 | goto P_AVAILABLE 635 | } 636 | if hasTask() { 637 | goto NO_P_AND_HAS_RUNNABLE_TASK 638 | } 639 | goto NO_P_AND_NO_RUNNABLE_TASK 640 | NEW_P: 641 | { 642 | pushNewP(newp) 643 | newp = nil 644 | goto P_AVAILABLE 645 | } 646 | P_AVAILABLE: 647 | { 648 | assert(hasP()) 649 | if hasTask() { 650 | } else { 651 | select { 652 | case newp = <-w.availablePchan: 653 | goto NEW_P 654 | case newTask = <-w.newTaskCh: 655 | case eiTask = <-w.runnableEventIntensiveTaskCh: 656 | case cpuTask = <-w.runnableCpuIntensiveTaskCh: 657 | } 658 | goto P_AVAILABLE_AND_HAS_RUNNABLE_TASK 659 | } 660 | } 661 | P_AVAILABLE_AND_HAS_RUNNABLE_TASK: 662 | { 663 | thisP := mustGetPnb() 664 | thisT, eiFlag, newFlag := mustGetTnb() 665 | w.taskSchArray[thisP.idx] = taskSchUnit{ 666 | validFlag: true, 667 | resumeT: time.Now(), 668 | taskPtr: thisT, 669 | } 670 | thisT.resume(thisP, eiFlag, newFlag) 671 | goto GOTO_NEXT_LOOP 672 | } 673 | NO_P_AND_NO_RUNNABLE_TASK: 674 | { 675 | select { 676 | case newp = <-w.availablePchan: 677 | goto NEW_P 678 | case newTask = <-w.newTaskCh: 679 | case eiTask = <-w.runnableEventIntensiveTaskCh: 680 | case cpuTask = <-w.runnableCpuIntensiveTaskCh: 681 | } 682 | goto NO_P_AND_HAS_RUNNABLE_TASK 683 | } 684 | NO_P_AND_HAS_RUNNABLE_TASK: 685 | { 686 | var timeoutCh <-chan time.Time 687 | timeout, idx := w.calcDurationToNextTimeSliceTimeout() 688 | var timer *time.Timer 689 | if idx < 0 { 690 | timeoutCh = nilCh 691 | } else { // validIdx 692 | assert(idx >= 0 && idx < len(w.taskSchArray)) 693 | timeoutNs := int64(timeout) 694 | if timeoutNs <= 0 { 695 | timeoutCh = closedCh 696 | } else { 697 | timer = time.NewTimer(timeout) 698 | timeoutCh = timer.C 699 | } 700 | } 701 | select { 702 | case <-timeoutCh: 703 | tu := w.taskSchArray[idx] 704 | tu.assertValid() 705 | w.taskSchArray[idx] = taskSchUnit{} 706 | tu.taskPtr.sendSuspendSignal() 707 | if timer != nil { 708 | timer.Stop() 709 | } 710 | goto GOTO_NEXT_LOOP 711 | case newp = <-w.availablePchan: 712 | if timer != nil { 713 | timer.Stop() 714 | } 715 | goto NEW_P 716 | } 717 | } 718 | GOTO_NEXT_LOOP: 719 | assert(newp == nil) 720 | continue 721 | } 722 | } 723 | 724 | func (w *Workers) GetMaxP() int { 725 | return cap(w.availablePchan) 726 | } 727 | 728 | func (w *Workers) Submit(fp0 func()) *TaskHandle { 729 | return w.submit(fp0, nil, nil, DefaultMaxTimeSlice, false) 730 | } 731 | 732 | func (w *Workers) Submit1(fp1 func(func())) *TaskHandle { 733 | return w.submit(nil, fp1, nil, DefaultMaxTimeSlice, false) 734 | } 735 | 736 | func (w *Workers) Submit2(fp1 func(func()), maxTimeSlice time.Duration) *TaskHandle { 737 | return w.submit(nil, fp1, nil, maxTimeSlice, false) 738 | } 739 | 740 | func (w *Workers) Submit3(fp2 func(func(func())), maxTimeSlice time.Duration, eiFlag bool) *TaskHandle { 741 | return w.submit(nil, nil, fp2, maxTimeSlice, eiFlag) 742 | } 743 | 744 | func (w *Workers) SubmitX(fp0 func(), fp1 func(func()), fp2 func(func(func())), maxTimeSlice time.Duration, eiFlag bool) *TaskHandle { 745 | return w.submit(fp0, fp1, fp2, maxTimeSlice, eiFlag) 746 | } 747 | 748 | func (w *Workers) submit(fp0 func(), fp1 func(func()), fp2 func(func(func())), maxTimeSlice time.Duration, eiFlag bool) *TaskHandle { 749 | if maxTimeSlice <= 0 { 750 | maxTimeSlice = DefaultMaxTimeSlice 751 | } 752 | task := Task{ 753 | validFlag: true, 754 | timing: taskSchTiming{}, 755 | stat: STAT_NEW, 756 | fp0: fp0, 757 | fp1: fp1, 758 | fp2: fp2, 759 | h: TaskHandle{ 760 | done: make(chan struct{}), 761 | yieldCh: make(chan *P, 1), 762 | resumeCh: make(chan *P, 1), 763 | }, 764 | maxTimeSlice: maxTimeSlice, 765 | initMaxTimeSlice: maxTimeSlice, 766 | w: w, 767 | pch: make(chan *P, 1), 768 | } 769 | if eiFlag { 770 | w.runnableEventIntensiveTaskCh <- &task 771 | } else { 772 | w.newTaskCh <- &task 773 | } 774 | return &task.h 775 | } 776 | 777 | func SetGlobalWorkers(w *Workers) { 778 | glWorkersLock.Lock() 779 | glWorkers = w 780 | glWorkersLock.Unlock() 781 | } 782 | 783 | func GetGlobalWorkers() (w *Workers) { 784 | glWorkersLock.Lock() 785 | w = glWorkers 786 | glWorkersLock.Unlock() 787 | return 788 | } 789 | 790 | func Submit(fp0 func()) *TaskHandle { 791 | return GetGlobalWorkers().submit(fp0, nil, nil, DefaultMaxTimeSlice, false) 792 | } 793 | 794 | func Submit1(fp1 func(func())) *TaskHandle { 795 | return GetGlobalWorkers().submit(nil, fp1, nil, DefaultMaxTimeSlice, false) 796 | } 797 | 798 | func Submit2(fp1 func(func()), maxTimeSlice time.Duration) *TaskHandle { 799 | return GetGlobalWorkers().submit(nil, fp1, nil, maxTimeSlice, false) 800 | } 801 | 802 | func Submit3(fp2 func(func(func())), maxTimeSlice time.Duration, eiFlag bool) *TaskHandle { 803 | return GetGlobalWorkers().submit(nil, nil, fp2, maxTimeSlice, eiFlag) 804 | } 805 | 806 | func SubmitX(fp0 func(), fp1 func(func()), fp2 func(func(func())), maxTimeSlice time.Duration, eiFlag bool) *TaskHandle { 807 | return GetGlobalWorkers().submit(fp0, fp1, fp2, maxTimeSlice, eiFlag) 808 | } 809 | 810 | /* 811 | func (w *Workers) Destroy() { 812 | close(w.exitCh) 813 | } 814 | */ 815 | 816 | func GetTraceMaxPdelay() time.Duration { 817 | return traceMaxPdelay 818 | } 819 | 820 | func CalcAutoP() int { 821 | nCPU := runtime.GOMAXPROCS(0) 822 | if nCPU <= 2 { 823 | return 1 824 | } 825 | if nCPU <= 5 { 826 | return nCPU - 1 827 | } 828 | if nCPU <= 7 { 829 | return nCPU - 2 830 | } 831 | return nCPU - (nCPU / 4) 832 | } 833 | 834 | func assert(b bool) { 835 | if b { 836 | } else { 837 | panic("unexpected") 838 | } 839 | } 840 | -------------------------------------------------------------------------------- /docs/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hnes/cpuworker/742c7fa7fe5c142f9cd9bf544281903d42a96e9e/docs/.DS_Store -------------------------------------------------------------------------------- /docs/img/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hnes/cpuworker/742c7fa7fe5c142f9cd9bf544281903d42a96e9e/docs/img/.DS_Store -------------------------------------------------------------------------------- /docs/img/big-picture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hnes/cpuworker/742c7fa7fe5c142f9cd9bf544281903d42a96e9e/docs/img/big-picture.png -------------------------------------------------------------------------------- /docs/img/cpuworker.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hnes/cpuworker/742c7fa7fe5c142f9cd9bf544281903d42a96e9e/docs/img/cpuworker.png -------------------------------------------------------------------------------- /docs/img/state-transition.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hnes/cpuworker/742c7fa7fe5c142f9cd9bf544281903d42a96e9e/docs/img/state-transition.png -------------------------------------------------------------------------------- /docs/img/step2-server-load.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hnes/cpuworker/742c7fa7fe5c142f9cd9bf544281903d42a96e9e/docs/img/step2-server-load.png -------------------------------------------------------------------------------- /docs/img/step3-server-load.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hnes/cpuworker/742c7fa7fe5c142f9cd9bf544281903d42a96e9e/docs/img/step3-server-load.png -------------------------------------------------------------------------------- /docs/img/step4-server-load.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hnes/cpuworker/742c7fa7fe5c142f9cd9bf544281903d42a96e9e/docs/img/step4-server-load.png -------------------------------------------------------------------------------- /example/demo.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The cpuworker Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "crypto/rand" 19 | "fmt" 20 | "hash/crc32" 21 | "log" 22 | _ "net/http/pprof" 23 | 24 | mathrand "math/rand" 25 | "net/http" 26 | "runtime" 27 | "time" 28 | 29 | "github.com/hnes/cpuworker" 30 | ) 31 | 32 | var glCrc32bs = make([]byte, 1024*256) 33 | 34 | func cpuIntensiveTask(amt int) uint32 { 35 | //ts := time.Now() 36 | var ck uint32 37 | for range make([]struct{}, amt) { 38 | ck = crc32.ChecksumIEEE(glCrc32bs) 39 | } 40 | //fmt.Println("log: crc32.ChecksumIEEE time cost (without checkpoint):", time.Now().Sub(ts)) 41 | return ck 42 | } 43 | 44 | func cpuIntensiveTaskWithCheckpoint(amt int, checkpointFp func()) uint32 { 45 | //ts := time.Now() 46 | var ck uint32 47 | for range make([]struct{}, amt) { 48 | ck = crc32.ChecksumIEEE(glCrc32bs) 49 | checkpointFp() 50 | } 51 | //fmt.Println("log: crc32.ChecksumIEEE time cost (with checkpoint):", time.Now().Sub(ts)) 52 | return ck 53 | } 54 | 55 | func handleChecksumWithoutCpuWorker(w http.ResponseWriter, _ *http.Request) { 56 | ts := time.Now() 57 | ck := cpuIntensiveTask(10000 + mathrand.Intn(10000)) 58 | w.Write([]byte(fmt.Sprintln("crc32 (without cpuworker):", ck, "time cost:", time.Now().Sub(ts)))) 59 | } 60 | 61 | func handleChecksumWithCpuWorkerAndHasCheckpoint(w http.ResponseWriter, _ *http.Request) { 62 | ts := time.Now() 63 | var ck uint32 64 | cpuworker.Submit1(func(checkpointFp func()) { 65 | ck = cpuIntensiveTaskWithCheckpoint(10000+mathrand.Intn(10000), checkpointFp) 66 | }).Sync() 67 | w.Write([]byte(fmt.Sprintln("crc32 (with cpuworker and checkpoint):", ck, "time cost:", time.Now().Sub(ts)))) 68 | } 69 | 70 | func handleChecksumSmallTaskWithCpuWorker(w http.ResponseWriter, _ *http.Request) { 71 | ts := time.Now() 72 | var ck uint32 73 | cpuworker.Submit(func() { 74 | ck = cpuIntensiveTask(10) 75 | }).Sync() 76 | w.Write([]byte(fmt.Sprintln("crc32 (with cpuworker and small task):", ck, "time cost:", time.Now().Sub(ts)))) 77 | } 78 | 79 | func handleDelay(w http.ResponseWriter, _ *http.Request) { 80 | t0 := time.Now() 81 | wCh := make(chan struct{}) 82 | go func() { 83 | time.Sleep(time.Millisecond) 84 | wCh <- struct{}{} 85 | }() 86 | <-wCh 87 | w.Write([]byte(fmt.Sprintf("delayed 1ms, time cost %s :)\n", time.Now().Sub(t0)))) 88 | } 89 | 90 | func handleDelayLoop(w http.ResponseWriter, _ *http.Request) { 91 | t0 := time.Now() 92 | for idx := range make([]byte, 10) { 93 | t0 := time.Now() 94 | wCh := make(chan struct{}) 95 | go func() { 96 | time.Sleep(time.Millisecond) 97 | wCh <- struct{}{} 98 | }() 99 | <-wCh 100 | w.Write([]byte(fmt.Sprintf("delayed 1ms loop, idx:%d , time cost %s :)\n", idx, time.Now().Sub(t0)))) 101 | } 102 | w.Write([]byte(fmt.Sprintf("delayed 1ms loop, final , total time cost %s :)\n", time.Now().Sub(t0)))) 103 | } 104 | 105 | func handleDelayLoopWithCpuWorker(w http.ResponseWriter, _ *http.Request) { 106 | cpuworker.Submit3(func(eventCall func(func())) { 107 | t0 := time.Now() 108 | for idx := range make([]byte, 10) { 109 | t0 := time.Now() 110 | wCh := make(chan struct{}) 111 | go func() { 112 | time.Sleep(time.Millisecond) 113 | wCh <- struct{}{} 114 | }() 115 | eventCall(func() { 116 | <-wCh 117 | w.Write([]byte(fmt.Sprintf("delayed 1ms loop with cpuworker, idx:%d , time cost %s :)\n", idx, time.Now().Sub(t0)))) 118 | }) 119 | } 120 | eventCall(func() { 121 | w.Write([]byte(fmt.Sprintf("delayed 1ms loop with cpuworker, final , total time cost %s :)\n", time.Now().Sub(t0)))) 122 | }) 123 | }, 0, true).Sync() 124 | } 125 | 126 | func main() { 127 | rand.Read(glCrc32bs) 128 | nCPU := runtime.GOMAXPROCS(0) 129 | cpuP := cpuworker.GetGlobalWorkers().GetMaxP() 130 | fmt.Println("GOMAXPROCS:", nCPU, "DefaultMaxTimeSlice:", cpuworker.DefaultMaxTimeSlice, 131 | "cpuWorkerMaxP:", cpuP, "length of crc32 bs:", len(glCrc32bs)) 132 | http.HandleFunc("/checksumWithCpuWorker", handleChecksumWithCpuWorkerAndHasCheckpoint) 133 | http.HandleFunc("/checksumSmallTaskWithCpuWorker", handleChecksumSmallTaskWithCpuWorker) 134 | http.HandleFunc("/checksumWithoutCpuWorker", handleChecksumWithoutCpuWorker) 135 | http.HandleFunc("/delay1ms", handleDelay) 136 | http.HandleFunc("/delay1msLoop", handleDelayLoop) 137 | http.HandleFunc("/delay1msLoopWithCpuWorker", handleDelayLoopWithCpuWorker) 138 | log.Fatal(http.ListenAndServe(":8080", nil)) 139 | } 140 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/hnes/cpuworker 2 | 3 | go 1.16 4 | -------------------------------------------------------------------------------- /priority-heap.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The cpuworker Authors 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package cpuworker 16 | 17 | type prioTaskHeapUnit struct { 18 | score float32 19 | seq uint64 20 | t *Task 21 | } 22 | 23 | // cmpPrio 24 | // 1: u1 > u2 25 | // 0: u1 == u2 26 | // -1: u1 < u2 27 | func cmpPrio(u1, u2 *prioTaskHeapUnit) int { 28 | if u1.score > u2.score { 29 | return 1 30 | } else { 31 | if u1.score < u2.score { 32 | return -1 33 | } else { 34 | if u1.seq > u2.seq { 35 | return 1 36 | } else { 37 | if u1.seq < u2.seq { 38 | return -1 39 | } else { 40 | return 0 41 | } 42 | } 43 | } 44 | } 45 | } 46 | 47 | type prioTaskHeap []prioTaskHeapUnit 48 | 49 | func (h prioTaskHeap) Len() int { return len(h) } 50 | 51 | func (h prioTaskHeap) Less(i, j int) bool { 52 | if cmpPrio(&h[i], &h[j]) == 1 { 53 | return true 54 | } else { 55 | return false 56 | } 57 | } 58 | 59 | func (h prioTaskHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } 60 | 61 | func (h *prioTaskHeap) Push(x interface{}) { 62 | // Push and Pop use pointer receivers because they modify the slice's length, 63 | // not just its contents. 64 | *h = append(*h, x.(prioTaskHeapUnit)) 65 | } 66 | 67 | func (h *prioTaskHeap) PeekTopest() prioTaskHeapUnit { 68 | assert(h.Len() > 0) 69 | return (*h)[0] 70 | } 71 | 72 | func (h *prioTaskHeap) Pop() interface{} { 73 | old := *h 74 | n := len(old) 75 | x := old[n-1] 76 | *h = old[0 : n-1] 77 | return x 78 | } 79 | 80 | type prioTaskQueue struct { 81 | // max allocated seq 82 | seq uint64 83 | h prioTaskHeap 84 | } 85 | 86 | func newPrioTaskQueue() *prioTaskQueue { 87 | return &prioTaskQueue{ 88 | h: make(prioTaskHeap, 0, 128), 89 | } 90 | } 91 | 92 | func (pq *prioTaskQueue) Len() int { 93 | return pq.h.Len() 94 | } 95 | 96 | func (pq *prioTaskQueue) Pop() prioTaskHeapUnit { 97 | assert(pq.Len() > 0) 98 | pu, ok := pq.h.Pop().(prioTaskHeapUnit) 99 | assert(ok) 100 | return pu 101 | } 102 | 103 | func (pq *prioTaskQueue) PeekTopest() prioTaskHeapUnit { 104 | assert(pq.Len() > 0) 105 | return pq.h.PeekTopest() 106 | } 107 | 108 | func (pq *prioTaskQueue) Push(t *Task, score float32) { 109 | seq := pq.seq + 1 110 | pq.seq = seq 111 | assert(seq != 0 && t != nil && score >= 0) 112 | pu := prioTaskHeapUnit{ 113 | score: score, 114 | seq: seq, 115 | t: t, 116 | } 117 | pq.h.Push(pu) 118 | return 119 | } 120 | --------------------------------------------------------------------------------