面试题答案
一键面试-
直接启动:
package main import ( "fmt" ) func worker() { fmt.Println("Goroutine is running") } func main() { go worker() fmt.Println("Main function continues") }
在上述代码中,通过
go
关键字直接启动一个Goroutine
,调用worker
函数。 -
带参数启动:
package main import ( "fmt" ) func workerWithParam(num int) { fmt.Printf("Goroutine with param %d is running\n", num) } func main() { for i := 0; i < 5; i++ { go workerWithParam(i) } fmt.Println("Main function continues") }
这里启动
Goroutine
时向函数workerWithParam
传递参数。
管理Goroutine所占用资源:
- 使用
defer
语句:在Goroutine
函数内部使用defer
关键字来确保相关资源在函数结束时被释放。例如:
这里在打开文件后使用package main import ( "fmt" ) func resourceHandler() { file, err := openFile("example.txt") if err != nil { return } defer file.Close() // 处理文件的逻辑 fmt.Println("Processing file...") } func main() { go resourceHandler() fmt.Println("Main function continues") }
defer
来关闭文件,即使resourceHandler
函数因各种原因提前结束,文件也能正确关闭。 - 使用
context.Context
:可以通过context.Context
来控制Goroutine
的生命周期,进而释放资源。例如:
这里通过package main import ( "context" "fmt" "time" ) func worker(ctx context.Context) { for { select { case <-ctx.Done(): fmt.Println("Goroutine is cancelled, cleaning up resources") // 清理资源的逻辑 return default: fmt.Println("Goroutine is working") time.Sleep(1 * time.Second) } } } func main() { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() go worker(ctx) time.Sleep(5 * time.Second) fmt.Println("Main function continues") }
context.WithTimeout
创建一个带超时的上下文,Goroutine
中的select
语句监听ctx.Done()
信号,当信号触发时进行资源清理并结束Goroutine
。