Cara Mengira dan Memaparkan Bilangan Goroutine Aktif
Dalam program anda, anda ingin memantau kiraan goroutin yang sedang aktif sambil serentak dequeuing dan enqueueing a queue. Semasa anda memberikan kod untuk mengurus baris gilir anda, anda telah bertanya tentang kaedah untuk mendapatkan semula bilangan goroutin aktif semasa.
Berikut ialah versi semakan kod anda menggunakan WaitGroup:
import ( "fmt" "sync" ) var element int func deen(wg *sync.WaitGroup, queue chan int) { for element := range queue { wg.Done() // Decrement the WaitGroup count upon completion fmt.Println("element is", element) if element%2 == 0 { fmt.Println("new element is", element) wg.Add(2) // Increment WaitGroup count for spawned goroutines queue <- (element*100 + 11) queue <- (element*100 + 33) } } } func main() { var wg sync.WaitGroup queue := make(chan int, 10) queue <- 1 queue <- 2 queue <- 3 queue <- 0 fmt.Println("initial active goroutines:", runtime.NumGoroutine()) for i := 0; i < 4; i++ { wg.Add(1) // Increment WaitGroup count for each spawned goroutine go deen(&wg, queue) } wg.Wait() // Wait for all goroutines to complete close(queue) fmt.Println("final active goroutines:", runtime.NumGoroutine()) fmt.Println("list length:", len(queue)) // Expect 0 }
Atas ialah kandungan terperinci Bagaimana Mengira Goroutine Aktif dengan Tepat dalam Program Go Serentak?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!