Skip to content

Should we defer wp.Close() #86

@drewgonzales360

Description

@drewgonzales360

Hi, I had question about when we need to Close(). I've added a small block to the example on the README.

		// HERE IS NEW CODE!!
		// Let's say we throw an error here and return. wp is still processing the first 500 tasks.
		if n == 500 {
			return fmt.Errorf("n == 500")
		}

Should we call defer wp.Close() immediately after we create it to avoid the workerpool continuing tasks it has in flight (unless people want the existing tasks to keep running)? Users may want to cancel all running tasks if they aren't able to submit or cancel all existing tasks if they throw an error else where. Both are valid, but I think it's worth calling out in the docs.

func main() {
	wp := workerpool.New(runtime.NumCPU())
	for i, n := 0, int64(1_000_000_000_000_000_000); n < 1_000_000_000_000_000_100; i, n = i+1, n+1 {
		n := n // https://golang.org/doc/faq#closures_and_goroutines
		id := fmt.Sprintf("task #%d", i)
		// Use Submit to submit tasks for processing. Submit blocks when no
		// worker is available to pick up the task.
		err := wp.Submit(id, func(_ context.Context) error {
			fmt.Println("isprime", n)
			if IsPrime(n) {
				fmt.Println(n, "is prime!")
			}
			return nil
		})
		// Submit fails when the pool is closed (ErrClosed) or being drained
		// (ErrDrained). Check for the error when appropriate.
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			return
		}

		// HERE IS NEW CODE!!
		// Let's say we throw an error here and return. wp is still processing the first 500 tasks.
		if n == 500 {
			return fmt.Errorf("n == 500")
		}
	}

	// Drain prevents submitting new tasks and blocks until all submitted tasks
	// complete.
	tasks, err := wp.Drain()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	}

	// Iterating over the results is useful if non-nil errors can be expected.
	for _, task := range tasks {
		// Err returns the error that the task returned after execution.
		if err := task.Err(); err != nil {
			fmt.Println("task", task, "failed:", err)
		}
	}

	// Close should be called once the worker pool is no longer necessary.
	if err := wp.Close(); err != nil {
		fmt.Fprintln(os.Stderr, err)
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions