### Create New Goroutine Pool in Go Source: https://github.com/panjf2000/ants/blob/dev/README.md This snippet initializes a new ants pool with a specified capacity. It uses the NewPool function from the ants library, requiring a capacity integer as input and returning a pool instance. This allows developers to set up a fixed-capacity goroutine pool at the start of their concurrent programs. ```go p, _ := ants.NewPool(10000) ``` -------------------------------- ### Configure non-blocking pool submission Source: https://context7.com/panjf2000/ants/llms.txt Shows how to configure a goroutine pool in non-blocking mode that returns immediately with an error when the pool is full, instead of waiting. The example demonstrates submitting many tasks to a small pool to trigger overload conditions. Depends on the ants/v2 library. ```go package main import ( "fmt" "time" "github.com/panjf2000/ants/v2" ) func main() { // Create non-blocking pool pool, err := ants.NewPool(5, ants.WithNonblocking(true)) if err != nil { panic(err) } defer pool.Release() submitted := 0 overloaded := 0 // Submit many tasks quickly to a small pool for i := 0; i < 100; i++ { err := pool.Submit(func() { time.Sleep(1 * time.Second) }) if err == ants.ErrPoolOverload { overloaded++ } else if err != nil { fmt.Printf("Unexpected error: %v\n", err) } else { submitted++ } } fmt.Printf("Submitted: %d, Overloaded: %d\n", submitted, overloaded) fmt.Printf("Pool running: %d, waiting: %d\n", pool.Running(), pool.Waiting()) time.Sleep(2 * time.Second) } ``` -------------------------------- ### Create MultiPoolWithFunc using LeastTasks strategy Source: https://context7.com/panjf2000/ants/llms.txt Demonstrates creating a multi-pool with a unified worker function and LeastTasks load balancing strategy. Tasks are distributed to the sub-pool with the least number of running tasks. The example processes custom Task structs with varying durations. Depends on ants/v2 library and standard sync packages. ```go package main import ( "fmt" "sync" "sync/atomic" "time" "github.com/panjf2000/ants/v2" ) type Task struct { ID int Duration time.Duration } func main() { var completed int32 var wg sync.WaitGroup // Worker function for processing tasks processTask := func(arg interface{}) { task := arg.(Task) time.Sleep(task.Duration) atomic.AddInt32(&completed, 1) fmt.Printf("Task %d completed\n", task.ID) wg.Done() } // Create MultiPoolWithFunc using LeastTasks strategy mp, err := ants.NewMultiPoolWithFunc(5, 20, processTask, ants.LeastTasks) if err != nil { panic(err) } defer mp.ReleaseTimeout(10 * time.Second) // Submit tasks with varying durations for i := 0; i < 100; i++ { wg.Add(1) task := Task{ ID: i, Duration: time.Duration(i%10+1) * time.Millisecond, } err := mp.Invoke(task) if err != nil { fmt.Printf("Invoke error: %v\n", err) wg.Done() } } wg.Wait() fmt.Printf("Completed %d tasks using LeastTasks strategy\n", atomic.LoadInt32(&completed)) } ``` -------------------------------- ### Submit Tasks to Goroutine Pool in Go Source: https://github.com/panjf2000/ants/blob/dev/README.md This example demonstrates submitting a function task to the ants pool for execution. The Submit function takes an anonymous function with no inputs or outputs, allowing for non-blocking task submission. It enables efficient handling of concurrent tasks without direct goroutine spawning. ```go ants.Submit(func(){}) ``` -------------------------------- ### Create type-safe generic pool with ants Source: https://context7.com/panjf2000/ants/llms.txt Demonstrates how to use generics with ants to create a type-safe worker pool that avoids interface{} conversions. The example shows a pool that processes int64 values and accumulates their sum using atomic operations. Depends on the ants/v2 library and standard sync packages. ```go package main import ( "fmt" "sync" "sync/atomic" "github.com/panjf2000/ants/v2" ) func main() { var sum int64 var wg sync.WaitGroup // Type-safe worker function workerFunc := func(num int64) { atomic.AddInt64(&sum, num) wg.Done() } // Create generic pool with type safety pool, err := ants.NewPoolWithFuncGeneric(10, workerFunc) if err != nil { panic(err) } defer pool.Release() // Invoke with strongly-typed arguments (no type assertion needed) for i := int64(0); i < 1000; i++ { wg.Add(1) err := pool.Invoke(i) if err != nil { fmt.Printf("Invoke failed: %v\n", err) wg.Done() } } wg.Wait() fmt.Printf("Type-safe sum: %d\n", atomic.LoadInt64(&sum)) } ``` -------------------------------- ### Configure Go Pool with Options Source: https://context7.com/panjf2000/ants/llms.txt Instantiates a goroutine pool with customizable options such as expiration duration for idle workers, pre-allocation of workers, blocking task limits, and a custom panic handler. Runtime capacity tuning is also demonstrated. ```go package main import ( "fmt" "log" "time" "github.com/panjf2000/ants/v2" ) func main() { // Pool with custom options pool, err := ants.NewPool( 100, ants.WithExpiryDuration(5*time.Second), ants.WithPreAlloc(true), ants.WithNonblocking(false), ants.WithMaxBlockingTasks(50), ants.WithPanicHandler(func(i interface{}) { log.Printf("Worker panic recovered: %v", i) }), ) if err != nil { panic(err) } defer pool.Release() // Submit task that might panic err = pool.Submit(func() { panic("simulated error") }) if err != nil { fmt.Printf("Submit failed: %v\n", err) } time.Sleep(100 * time.Millisecond) fmt.Println("Pool continued running after panic") // Tune capacity at runtime pool.Tune(200) fmt.Printf("Pool capacity tuned to: %d\n", pool.Cap()) } ``` -------------------------------- ### Create Ants Pool with Pre-allocation (Go) Source: https://github.com/panjf2000/ants/blob/dev/README.md Demonstrates how to create a new Ants pool with pre-allocated memory for the goroutine queue. This is useful for scenarios requiring a large capacity and long-running tasks to reduce memory allocation overhead. The `WithPreAlloc` option enables this feature. ```Go p, _ := ants.NewPool(100000, ants.WithPreAlloc(true)) ``` -------------------------------- ### Manage Go Pool Lifecycle with Release and Reboot Source: https://context7.com/panjf2000/ants/llms.txt This Go code snippet demonstrates how to create a goroutine pool, submit tasks, gracefully release the pool with a timeout to ensure all tasks complete, and then reboot the pool for reuse. It utilizes the ants library for pool management. ```go package main import ( "fmt" "time" "github.com/panjf2000/ants/v2" ) func main() { pool, err := ants.NewPool(10) if err != nil { panic(err) } // Submit some tasks for i := 0; i < 20; i++ { pool.Submit(func() { time.Sleep(100 * time.Millisecond) }) } fmt.Printf("Pool running: %d\n", pool.Running()) // Release with timeout (wait for workers to finish) err = pool.ReleaseTimeout(5 * time.Second) if err != nil { fmt.Printf("Release error: %v\n", err) } else { fmt.Println("Pool released gracefully") } // Check if pool is closed if pool.IsClosed() { fmt.Println("Pool is closed") } // Reboot the pool for reuse pool.Reboot() fmt.Println("Pool rebooted") // Submit tasks to rebooted pool err = pool.Submit(func() { fmt.Println("Task running on rebooted pool") }) if err != nil { fmt.Printf("Submit after reboot failed: %v\n", err) } time.Sleep(200 * time.Millisecond) pool.Release() } ``` -------------------------------- ### Go PoolWithFunc for Unified Function Execution Source: https://context7.com/panjf2000/ants/llms.txt Creates a goroutine pool using `PoolWithFunc`, where all goroutines execute a single specified function, but with different arguments. This enhances type safety and performance for scenarios involving repetitive function calls with varying inputs. ```go package main import ( "fmt" "sync" "sync/atomic" "github.com/panjf2000/ants/v2" ) func main() { var sum int32 var wg sync.WaitGroup // Worker function that will be executed by all goroutines workerFunc := func(i interface{}) { num := i.(int) atomic.AddInt32(&sum, int32(num)) wg.Done() } // Create pool with unified function pool, err := ants.NewPoolWithFunc(10, workerFunc) if err != nil { panic(err) } defer pool.Release() // Invoke function with different arguments for i := 0; i < 1000; i++ { wg.Add(1) err := pool.Invoke(i) if err != nil { fmt.Printf("Invoke failed: %v\n", err) wg.Done() } } wg.Wait() fmt.Printf("Sum result: %d (expected: 499500)\n", atomic.LoadInt32(&sum)) } ``` -------------------------------- ### Create MultiPool with RoundRobin load balancing Source: https://context7.com/panjf2000/ants/llms.txt Shows how to create multiple goroutine pools with load balancing to reduce lock contention in high-concurrency scenarios. Uses RoundRobin strategy to distribute tasks across 10 sub-pools. Each sub-pool has a capacity of 100 workers. Depends on ants/v2 library and standard sync packages. ```go package main import ( "fmt" "sync" "sync/atomic" "time" "github.com/panjf2000/ants/v2" ) func main() { var counter int32 var wg sync.WaitGroup // Create MultiPool with 10 sub-pools, each with capacity 100 // Using RoundRobin load balancing strategy mp, err := ants.NewMultiPool(10, 100, ants.RoundRobin) if err != nil { panic(err) } defer mp.ReleaseTimeout(5 * time.Second) // Submit 10000 tasks across multiple pools for i := 0; i < 10000; i++ { wg.Add(1) err := mp.Submit(func() { defer wg.Done() atomic.AddInt32(&counter, 1) time.Sleep(1 * time.Millisecond) }) if err != nil { fmt.Printf("Submit error: %v\n", err) wg.Done() } } wg.Wait() fmt.Printf("Total tasks completed: %d\n", atomic.LoadInt32(&counter)) fmt.Printf("MultiPool stats - Running: %d, Cap: %d, Waiting: %d\n", mp.Running(), mp.Cap(), mp.Waiting()) } ``` -------------------------------- ### Tune Goroutine Pool Capacity in Go Source: https://github.com/panjf2000/ants/blob/dev/README.md This code shows how to dynamically adjust the capacity of an ants pool at runtime using the Tune method. It accepts a new capacity integer, enabling scaling based on workload needs. The operation is thread-safe, allowing safe calls from multiple goroutines without contention issues. ```go pool.Tune(1000) // Tune its capacity to 1000 pool.Tune(100000) // Tune its capacity to 100000 ``` -------------------------------- ### Create Custom Go Pool with Fixed Capacity Source: https://context7.com/panjf2000/ants/llms.txt Creates a new goroutine pool with a specified fixed capacity, limiting the number of concurrently running goroutines. This helps control resource usage and prevent overwhelming the system. ```go package main import ( "fmt" "sync" "time" "github.com/panjf2000/ants/v2" ) func main() { // Create pool with capacity of 10 workers pool, err := ants.NewPool(10) if err != nil { panic(err) } defer pool.Release() var wg sync.WaitGroup // Submit 100 tasks, only 10 will run concurrently for i := 0; i < 100; i++ { wg.Add(1) taskID := i err := pool.Submit(func() { defer wg.Done() time.Sleep(100 * time.Millisecond) fmt.Printf("Task %d completed by pool with %d running workers\n", taskID, pool.Running()) }) if err != nil { fmt.Printf("Submit error: %v\n", err) wg.Done() } } wg.Wait() fmt.Printf("Pool stats - Running: %d, Free: %d, Waiting: %d\n", pool.Running(), pool.Free(), pool.Waiting()) } ``` -------------------------------- ### Reboot Ants Pool (Go) Source: https://github.com/panjf2000/ants/blob/dev/README.md Illustrates how to reboot an Ants pool after it has been released. Rebooting allows the pool to accept new tasks again, effectively resetting its state. This function is useful for reusing a pool that was previously shut down. ```Go // A pool that has been released can be still used after calling the Reboot(). pool.Reboot() ``` -------------------------------- ### Submit Tasks to Default Go Pool Source: https://context7.com/panjf2000/ants/llms.txt Submits tasks to the global default goroutine pool. This pool has an unlimited capacity and blocks until a worker is available. It's suitable for general-purpose concurrent task execution. ```go package main import ( "fmt" "sync" "github.com/panjf2000/ants/v2" ) func main() { defer ants.Release() var wg sync.WaitGroup // Submit 1000 tasks to default pool for i := 0; i < 1000; i++ { wg.Add(1) taskID := i err := ants.Submit(func() { defer wg.Done() fmt.Printf("Task %d running\n", taskID) }) if err != nil { fmt.Printf("Submit failed: %v\n", err) wg.Done() } } wg.Wait() fmt.Println("All tasks completed") } ``` -------------------------------- ### Release Ants Pool (Go) Source: https://github.com/panjf2000/ants/blob/dev/README.md Shows how to release resources associated with an Ants pool. This can be done with or without a timeout. Releasing the pool stops new tasks from being accepted and waits for existing tasks to complete. ```Go pool.Release() ``` ```Go pool.ReleaseTimeout(time.Second * 3) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.