// Start initializes the worker goroutines. func (gp *GoroutinePool) Start() { for i := 1; i <= gp.numWorkers; i++ { gp.wg.Add(1) go gp.worker(i) } }
// worker is a function that each goroutine will run. func (gp *GoroutinePool) worker(id int) { defer gp.wg.Done()
for task := range gp.tasks { // Simulate processing a task fmt.Printf("Worker %d processing task %d\n", id, task.id) time.Sleep(1 * time.Second) // Simulate a time-consuming task } }
// Submit adds a task to the pool's task queue. func (gp *GoroutinePool) Submit(task Task) { gp.tasks <- task }
// Stop gracefully shuts down the pool after all tasks are processed. func (gp *GoroutinePool) Stop() { close(gp.tasks) // Close the task channel to signal workers to stop. gp.wg.Wait() // Wait for all workers to finish. }
func main() { // Create a GoroutinePool with 3 workers and a task queue size of 10. pool := NewGoroutinePool(3, 10)
// Start the workers. pool.Start()
// Submit tasks to the pool. for i := 1; i <= 10; i++ { pool.Submit(Task{id: i}) }
// Stop the pool and wait for all tasks to complete. pool.Stop()
fmt.Println("All tasks have been processed.") }
Golang Sorting
Binary Search
// binarySearch function performs binary search on a sorted slice. // Returns the index of the target if found, otherwise -1. func binarySearch(arr []int, target int) int { low, high := 0, len(arr)-1
for low <= high { mid := low + (high-low)/2 // Avoid potential overflow if arr[mid] == target { return mid } if arr[mid] < target { low = mid + 1 } else { high = mid - 1 } }
return -1 // Target not found }
Bubble Search
// bubbleSort function sorts a slice using the Bubble Sort algorithm. func bubbleSort(arr []int) { n := len(arr) for i := 0; i < n-1; i++ { for j := 0; j < n-i-1; j++ { if arr[j] > arr[j+1] { // Swap arr[j] and arr[j+1] arr[j], arr[j+1] = arr[j+1], arr[j] } } } }
func fibonaci(i int) (ret int) { if i == 0 { return 0 } if i == 1 { return 1 } return fibonaci(i-1) + fibonaci(i-2) }