package main

import (
	"fmt"
	"runtime"
	"sync"
	"sync/atomic"
)

func main() {
	fmt.Println("goroutine di awal    :", runtime.NumGoroutine())

	const jumlah = 1000
	var siap atomic.Int32
	var wg sync.WaitGroup
	mulai := make(chan struct{})

	wg.Add(jumlah)
	for range jumlah {
		go func() {
			defer wg.Done()
			siap.Add(1)
			<-mulai // semua goroutine menunggu sinyal mulai
		}()
	}

	// tunggu sampai 1000 goroutine benar-benar tercipta
	for siap.Load() < jumlah {
		runtime.Gosched()
	}

	fmt.Println("goroutine saat sibuk :", runtime.NumGoroutine())
	close(mulai) // satu channel tutup membebaskan 1000 goroutine
	wg.Wait()
	fmt.Println("goroutine di akhir   :", runtime.NumGoroutine())
}
