Goroutine is a lightweight execution thread that executes tasks in parallel in Go. It is created through the go keyword and has concurrency, lightweight and communication capabilities. In practical cases, concurrent crawlers use Goroutines to crawl URLs in parallel, and use channels to limit the number of concurrent Goroutines to optimize performance and system resources.
Goroutine in Go function
Goroutine is a lightweight execution thread in Go and can be executed in parallel. They allow us to write concurrent and efficient code.
Create Goroutine
Create a Goroutine using the go
keyword, followed by a function call:
func main() { go hello() } func hello() { fmt.Println("Hello world!") }
goroutine Benefits
Practical case: Concurrent crawler
Use Goroutine to create a concurrent crawler:
package main import ( "fmt" "sync" "time" ) // URL 队列 var urls = []string{"url1", "url2", "url3"} // 用于确保并发安全 var wg sync.WaitGroup // 抓取函数 func fetch(url string) { // 模拟抓取 fmt.Println("抓取", url) time.Sleep(100 * time.Millisecond) wg.Done() } func main() { // 限制并发 goroutine 的数量 maxConcurrency := 3 // 创建一个信道来限制并发 goroutine 的数量 sem := make(chan struct{}, maxConcurrency) // 为每个 URL 创建一个 goroutine for _, url := range urls { sem <- struct{}{} wg.Add(1) go func(url string) { defer wg.Done() defer func() { <-sem }() fetch(url) }(url) } // 等待所有 goroutine 完成 wg.Wait() }
In this example, fetch
The function crawls URLs in parallel, using channels (sem
) to limit up to 3 goroutines to run at the same time. This helps balance performance and system resources.
The above is the detailed content of goroutine of golang function. For more information, please follow other related articles on the PHP Chinese website!