Home >Backend Development >Golang >Collaboration between golang function and goroutine
In Go programming, functions and goroutines work together to achieve concurrency. A goroutine is created in a function, and the local variables of the function are visible in the goroutine. Goroutine can be used in actual combat for concurrent processing tasks, such as concurrent file uploads. Efficiency can be improved by creating goroutines responsible for uploading different files. When using goroutine, please note: Create goroutine in an appropriate amount to avoid resource shortage; goroutine has no return value, and you need to use concurrency primitives to obtain results; goroutine cannot be stopped or canceled directly.
In the Go programming language, goroutine is a concurrency mechanism that can create lightweight threads to execute code. Functions and goroutines work together to achieve efficient concurrent programming.
Goroutine can be created inside the function, and the local variables and constants in the function are visible in the goroutine. When a Goroutine ends, its local variables and constants will be recycled.
The following example shows how to create a goroutine and pass parameters in a function:
package main import ( "fmt" "time" ) func printHello(name string) { fmt.Printf("Hello, %s!\n", name) } func main() { go printHello("World") time.Sleep(1 * time.Second) }
In the above example, the main
function creates a goroutine and passes in parameters "World"
. The goroutine executes the printHello
function and prints out "Hello, World!\n"
.
Consider a use case that requires concurrent uploading of multiple files:
package main import ( "context" "fmt" "io" "os" "path/filepath" "time" "cloud.google.com/go/storage" ) func uploadFile(w io.Writer, bucketName, objectName string) error { ctx := context.Background() client, err := storage.NewClient(ctx) if err != nil { return fmt.Errorf("storage.NewClient: %v", err) } defer client.Close() f, err := os.Open(objectName) if err != nil { return fmt.Errorf("os.Open: %v", err) } defer f.Close() ctx, cancel := context.WithTimeout(ctx, time.Second*30) defer cancel() o := client.Bucket(bucketName).Object(objectName) wc := o.NewWriter(ctx) if _, err := io.Copy(wc, f); err != nil { return fmt.Errorf("io.Copy: %v", err) } if err := wc.Close(); err != nil { return fmt.Errorf("Writer.Close: %v", err) } fmt.Fprintf(w, "File %v uploaded to %v.\n", objectName, bucketName) return nil } func main() { bucketName := "bucket-name" objectNames := []string{"file1.txt", "file2.txt", "file3.txt"} for _, objectName := range objectNames { go uploadFile(os.Stdout, bucketName, objectName) } }
In this case, the main
function is created A list of goroutines, each goroutine reads a file from the operating system and uploads it to Google Cloud Storage. This allows applications to upload multiple files concurrently, significantly improving performance.
You need to pay attention to the following when using goroutine:
The above is the detailed content of Collaboration between golang function and goroutine. For more information, please follow other related articles on the PHP Chinese website!