Concurrent Programming Guide in Golang Standard Library
Introduction:
Concurrent programming is an important means to solve program performance problems and achieve efficient use of computing resources. In the Golang programming language, a wealth of concurrent programming tools and methods are provided. This article will introduce some common concurrent programming techniques in the Golang standard library, and illustrate their usage and precautions through specific code examples.
package main import ( "fmt" "time" ) func printNumbers() { for i := 0; i < 5; i++ { fmt.Printf("%d ", i) time.Sleep(time.Millisecond * 500) } } func printLetters() { for i := 'A'; i < 'F'; i++ { fmt.Printf("%c ", i) time.Sleep(time.Millisecond * 500) } } func main() { go printNumbers() // 启动一个Goroutine,打印数字 go printLetters() // 启动另一个Goroutine,打印字母 time.Sleep(time.Second * 3) // 等待两个Goroutine执行完毕 fmt.Println("Done") }
In the above code, we define two functions printNumbers
and printLetters
respectively, and pass ## The #go keyword starts them as two Goroutines respectively. Use the
time.Sleep function to wait for the two Goroutines to complete execution. You can see that numbers and letters are output alternately in the output results.
package main import ( "fmt" "time" ) func worker(id int, jobs <-chan int, results chan<- int) { for job := range jobs { fmt.Printf("Worker %d started job %d ", id, job) time.Sleep(time.Second) fmt.Printf("Worker %d finished job %d ", id, job) results <- job * 2 } } func main() { numJobs := 5 jobs := make(chan int, numJobs) results := make(chan int, numJobs) numWorkers := 3 for w := 1; w <= numWorkers; w++ { go worker(w, jobs, results) } for j := 1; j <= numJobs; j++ { jobs <- j } close(jobs) for a := 1; a <= numJobs; a++ { result := <-results fmt.Println("Result:", result) } }
worker function, which is used to receive the number passed in by the jobs channel and perform the corresponding Processing, the results are returned through the results channel. In the main function, we created two channels, jobs and results, respectively, and passed the jobs channel to three Goroutines for execution. Then, send 5 jobs to the jobs channel through a for loop and close the channel. Finally, the return result of the results channel is received through the for loop and output.
package in Golang provides the WaitGroup type to implement this function. The following is an example of using WaitGroup:
package main import ( "fmt" "sync" "time" ) func worker(id int, wg *sync.WaitGroup) { defer wg.Done() fmt.Printf("Worker %d starting ", id) time.Sleep(time.Second) fmt.Printf("Worker %d done ", id) } func main() { var wg sync.WaitGroup numWorkers := 3 wg.Add(numWorkers) for w := 1; w <= numWorkers; w++ { go worker(w, &wg) } wg.Wait() fmt.Println("All workers done") }
worker function, which receives a WaitGroup parameter, executes the corresponding task, and executes the task After the execution is completed, the WaitGroup is notified through the
Done method. In the main function, we create a WaitGroup variable and specify the number of Goroutines to wait for through the
Add method. Then, use the
go keyword to start the corresponding number of Goroutines and pass the WaitGroup pointer to each Goroutine. Finally, wait for all Goroutine execution to complete through the
Wait method.
Through the concurrent programming tools and methods provided in the Golang standard library, we can easily implement high-concurrency programs. This article introduces common concurrent programming techniques such as Goroutine, Channel, and WaitGroup, and illustrates them with specific code examples. I hope that readers can better master the concurrent programming skills in Golang and improve the performance and operating efficiency of the program through studying this article.
The above is the detailed content of Concurrent Programming Guide: Exploring Parallelism in the Golang Standard Library. For more information, please follow other related articles on the PHP Chinese website!