This is a creation in Article, where the information may have evolved or changed.
Package Mainimport ("Container/heap" "FMT" "Log" "Math/rand" "Time") const (maxqueuelength = 10MaxRequesters = 2Seconds = 2e9) Type Request func () func main () {requests: = Make (chan Request) for I: = 0; i < maxrequesters; i++ {Go requester (r equests)}newbalancer (2). Balance (requests)}func requester (work Chan Request) {for {time]. Sleep (time. Duration (Rand. Int63n (Maxrequesters * Seconds))) Work <-func () {r: = rand. Int63n (maxrequesters*seconds) + 10time. Sleep (time. Duration (R))}}}func newbalancer (size int) *balancer {done: = Make (chan *worker, size) B: = &balancer{pool:make (pool, 0 , size), done:done,}for I: = 0; i < size; i++ {w: = &worker{id:i, Requests:make (Chan Request, maxqueuelength)}heap. Push (&b.pool, W) go w.work (done)}return b}type Balancer struct {pool Pooldone chan *worker}func (b *balancer) Balance (r Equests Chan Request) {for {select {case req: = <-requests:b.dispatch (req) log. Printf ("New request,%s", B.pool) Case w: = <-b.done:b.completed (w) log. Printf ("ReQuest finished,%s ", B.pool)}}}func (b *balancer) dispatch (req Request) {w: = heap. Pop (&b.pool). (*worker) w.requests <-reqw.pending++heap. Push (&b.pool, W)}//drain the Heapfunc (b *balancer) completed (W *worker) {w.pending--heap.remove (&b.pool, W.index) heap. Push (&b.pool, W)}type pool []*workertype Worker struct {id intpending intrequests chan requestindex int}func (w *worker) work (do Chan *worker) {for {req: = <-w.requests//req was therefore of type Request, it is a functionreq ( )//we Execute It!done <-w}}func (w *worker) string () string {return FMT. Sprintf ("W%d{pending:%d}", W.id, W.pending)}func (P pool) len () int {return Len (P)}func (P pool) Less (i, J int) bool {RET Urn p[i].pending < P[j].pending}func (P *pool) Swap (i, J int) {A: = *pa[i], a[j] = a[j], A[i]a[i].index = Ia[j].index = J}func (P *pool) Push (i interface{}) {w: = i. (*worker) A: = *pn: = Len (a) W.index = NA = Append (A, W) *p = A}func (P *pool) Pop () interface{} {A: = *pN: = Len (a) W: = A[n-1]w.index = -1*p = A[0:n-1]return W}
Heap as a data structure, do not mix with the operating system inside the stack and the like.
Common usage is heap sorting and priority queuing
The key operation is the initialization of the heap, as well as inserting elements and deleting elements
+10level:2exp:20/50