OneCompiler

Example of Go Routine concurrency and Wait Group

217

package main

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

func main() {
shadowChannel := make(chan string)
extraChannel := make(chan string)
var wg sync.WaitGroup

// Launching goroutines to send messages to shadowChannel
for i := 0; i <= 20; i++ {
	wg.Add(1)
	go callGoRoutine(i, shadowChannel, &wg)
}

// Launching goroutines to send messages to extraChannel
for i := 0; i <= 5; i++ {
	wg.Add(1)
	go callExtraRoutine(i, extraChannel, &wg)
}

// Closing channels after all goroutines have finished
go func() {
	wg.Wait()
	close(shadowChannel)
	close(extraChannel)
}()

// Using select to handle messages from both channels
for {
	select {
	case value, ok := <-shadowChannel:
		if ok {
			fmt.Println("Received from shadowChannel:", value)
		} else {
			shadowChannel = nil
		}
	case value, ok := <-extraChannel:
		if ok {
			fmt.Println("Received from extraChannel:", value)
		} else {
			extraChannel = nil
		}
	}
	
	// Exit the loop if both channels are closed
	if shadowChannel == nil && extraChannel == nil {
		break
	}
}

}

func callGoRoutine(index int, myNewChannel chan string, wg *sync.WaitGroup) {
defer wg.Done()
myNewChannel <- "go routine " + strconv.Itoa(index)
}

func callExtraRoutine(index int, myNewChannel chan string, wg *sync.WaitGroup) {
defer wg.Done()
time.Sleep(500 * time.Millisecond) // Simulate some work
myNewChannel <- "extra routine " + strconv.Itoa(index)
}