Sobes.tech
Middle

How can you test the operation of a goroutine through a channel?

sobes.tech AI

Answer from AI

You can use channel closing semantics. The sender closes the channel when all data has been sent, and the receiver can read all data and determine completion by the channel closure.

package main

import (
	"fmt"
	"sync"
	"time"
)

func worker(done chan<- struct{}, wg *sync.WaitGroup) {
	defer wg.Done()
	fmt.Println("Goroutine is working...")
	time.Sleep(time.Second) // Simulate work
	fmt.Println("Goroutine has finished work.")
	// Send completion signal via channel
	//done <- struct{}{} // You can use an empty struct
}

func main() {
	var wg sync.WaitGroup
	done := make(chan struct{}) // Channel for signaling completion

	wg.Add(1)
	go worker(done, &wg)

	// Wait for all goroutines to finish or receive a completion signal
	go func() {
		wg.Wait()
		close(done) // Close the channel after all goroutines are done
	}()

	// Receive completion signal
	<-done
	fmt.Println("Main goroutine received completion signal.")
}

Using select:

package main

import (
	"fmt"
	"time"
)

func worker(done chan<- bool) {
	fmt.Println("Goroutine is working...")
	time.Sleep(time.Second) // Simulate work
	fmt.Println("Goroutine has finished work.")
	done <- true // Send completion signal
}

func main() {
	done := make(chan bool) // Channel for signaling completion

	go worker(done)

	// Wait for completion signal
	select {
	case <-done:
		fmt.Println("Main goroutine received completion signal.")
	case <-time.After(2 * time.Second): // Timeout if goroutine hangs
		fmt.Println("Timeout: goroutine did not finish in time.")
	}
}