Home > Backend Development > Golang > goroutine of golang function

goroutine of golang function

王林
Release: 2024-04-19 17:39:02
Original
842 people have browsed it

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 of golang function

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!")
}
Copy after login

goroutine Benefits

  • # Concurrency: Goroutine can perform multiple tasks at the same time, thereby improving performance.
  • Lightweight: Goroutine is much lighter than threads and has lower overhead.
  • Communication: Goroutines can communicate easily through channels.

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()
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template