Question: Write a startup function createTask(names[]string) in golang. Function: Start n threads, the number of threads is the length of names, and the thread name is the value of names. It is necessary to wait for all threads to start before executing the function and returning
Code: Here is a function written in Golang createTask
that starts names
as many goroutines as there are names in the slice and waits for them all to finish before returning:
package main
import (
"fmt"
"sync"
)
func createTask(names []string) {
var wg sync.WaitGroup
for _, name := range names {
wg.Add(1)
go func(n string) {
defer wg.Done()
fmt.Printf("线程 %s 启动\n", n)
// 在这里可以执行线程需要做的工作
}(name)
}
wg.Wait() // 等待所有线程完成
fmt.Println("所有线程已启动完成,函数返回")
}
func main() {
names := []string{"Thread1", "Thread2", "Thread3"}
createTask(names)
}