panjf2000 / ants

🐜🐜🐜 ants is the most powerful and reliable pooling solution for Go.
https://ants.andypan.me/
MIT License
12.69k stars 1.36k forks source link

[Question]: set max block task, but not return err when block task num more than set value #304

Closed Suvian-wy closed 9 months ago

Suvian-wy commented 9 months ago

Questions with details

OS: macos go version: 1.21.1

I have settes the max block task count, expected to get err when I summit 7 8 9 task, but i get nothing, each task is run success

Code snippets (optional)

package main

import (
    "fmt"
    "log"
    "sync"
    "time"

    "github.com/panjf2000/ants/v2"
)

var wg sync.WaitGroup

func main() {
    options := ants.Options{
        ExpiryDuration:   time.Duration(10) * time.Second,
        PreAlloc:         true,
        MaxBlockingTasks: 2,
        Nonblocking:      false,
    }

    poolSize := 5
    p, err := ants.NewPoolWithFunc(poolSize, processTask, ants.WithOptions(options))
    if err != nil {
        log.Fatalf("Failed to create goroutine pool: %v", err)
    }
    defer p.Release()

    numTasks := 10

    for i := 0; i < numTasks; i++ {
        wg.Add(1)
        task := i

        err := p.Invoke(task)
        if err != nil {
            log.Printf("Failed to submit task %d: %v", task, err)
            wg.Done()
        } 
    }

    // Wait for all tasks to be processed using the WaitGroup
    wg.Wait()
    fmt.Println("All tasks processed")
}

func processTask(task interface{}) {
    value := task.(int)
    fmt.Printf("Processing task with value: %d\n", value)
    time.Sleep(1 * time.Second)

    // Decrement the WaitGroup counter when the task is done
    wg.Done()
}
panjf2000 commented 9 months ago

Sorry for the delay.

The reason why your program didn't get an ErrPoolOverload, is that it got blocked at line err := p.Invoke(task) in the sixth task, it would wait until the first five tasks to finish, then the rest of tasks would be submitted successfully.

You can check out the right way to test this feature: https://github.com/panjf2000/ants/blob/27685ba40874decc26c0e6e845a969412059772d/ants_test.go#L469-L502