Home Backend Development Golang Goroutines and Channels: Concurrency Patterns in Go

Goroutines and Channels: Concurrency Patterns in Go

Dec 13, 2024 am 05:55 AM

Concurrency allows us to handle multiple tasks independently from each other. Goroutines are a simple way to process multiple tasks independently. In this post we progressively enhance a http handler which accepts files an explore various concurrency patterns in Go utilizing channels and the sync package.

Setup

Before getting into concurrency patterns let’s set the stage. Imagine we have a HTTP handler that accepts multiple files via form and processes the files in some way.

func processFile(file multipart.File) {
   // do something with the file
   fmt.Println("Processing file...")
   time.Sleep(100 * time.Millisecond) // Simulating file processing time
}
func UploadHandler(w http.ResponseWriter, r *http.Request) {
   // limit to 10mb 
   if err := r.ParseMultipartForm(10 << 20); err != nil {
       http.Error(w, "Unable to parse form", http.StatusBadRequest)
       return 
   }
   // iterate through all files and process them sequentially 
   for _, file := range r.MultipartForm.File["files"] {
       f, err := file.Open()
       if err != nil {
          http.Error(w, "Unable to read file", http.StatusInternalServerError)
          return
       }
       processFile(f)
       f.Close()
   }
}
Copy after login
Copy after login

In the example above we receive files from a form and process them sequentially. If 10 files are uploaded it would take 1 second to complete the process and send a response to the client.
When handling many files this can become a bottleneck, however with Go's concurrency support we can easily solve this issue.

Wait Groups

To solve this we can process files concurrently. To spawn a new goroutine we can prefix a function call with the go keyword e.g. go processFile(f). However as goroutines are non blocking the handler might return before the process is finished, leaving files possibly unprocessed or returning an incorrect state. To wait for the processing of all files we can utilize sync.WaitGroup.
A WaitGroup waits for a number of goroutines to finish, for each goroutine we spawn we additionally should increase the counter in the WaitGroup this can be done with the Add function. When a goroutine is finished Done should be called so the counter is decreased by one. Before returning from the function Wait should be called which is blocking until the counter of the WaitGroup is 0.

func UploadHandler(w http.ResponseWriter, r *http.Request) {
   if err := r.ParseMultipartForm(10 << 20); err != nil {
       http.Error(w, "Unable to parse form", http.StatusBadRequest)
       return
   }

   // create WaitGroup 
   var wg sync.WaitGroup 
   for _, file := range r.MultipartForm.File["files"] {
       f, err := file.Open()
       if err != nil {
          http.Error(w, "Unable to read file", http.StatusInternalServerError)
          return
       }

       wg.Add(1) // Add goroutine to the WaitGroup by incrementing the WaitGroup counter, this should be called before starting a goroutine
       // Process file concurrently
       go func(file multipart.File) {
           defer wg.Done() // decrement the counter by calling Done, utilize defer to guarantee that Done is called. 
           defer file.Close()
           processFile(f)
       }(f)
   }

   // Wait for all goroutines to complete
   wg.Wait()
   fmt.Fprintln(w, "All files processed successfully!")
}
Copy after login
Copy after login

Now for each uploaded file a new goroutine is spawned this could overwhelm the system. One solution is to limit the number of spawned goroutines.

Limiting Concurrency With A Semaphore

A Semaphore is just a variable we can use to control access to common resources by multiple threads or in this case goroutines.

In Go we can utilize buffered channels to implement a semaphore.

Channels

Before getting into the implementation let's look at what channels are and the difference between buffered and unbuffered channels.

Channels are a pipe through which we can send and receive data to communicate safely between go routines.
Channels must be created with the make function.

func processFile(file multipart.File) {
   // do something with the file
   fmt.Println("Processing file...")
   time.Sleep(100 * time.Millisecond) // Simulating file processing time
}
func UploadHandler(w http.ResponseWriter, r *http.Request) {
   // limit to 10mb 
   if err := r.ParseMultipartForm(10 << 20); err != nil {
       http.Error(w, "Unable to parse form", http.StatusBadRequest)
       return 
   }
   // iterate through all files and process them sequentially 
   for _, file := range r.MultipartForm.File["files"] {
       f, err := file.Open()
       if err != nil {
          http.Error(w, "Unable to read file", http.StatusInternalServerError)
          return
       }
       processFile(f)
       f.Close()
   }
}
Copy after login
Copy after login

Channels have a special operator <- which is utilized to send or read from a channel.
Having the operator point at the channel ch <- 1 sends data to the channel, if the arrow points away from the channel <-ch the value will be received. Send and receive operations are blocking by default this means each operation will wait until the other side is ready.

Goroutines and Channels: Concurrency Patterns in Go
The animation visualizes a producer sending the value 1 through an unbuffered channel and the consumer reading from the channel.

If the producer can send events faster than the consumer can handle then we have the option to utilize a buffered channel to queue up multiple messages without blocking the producer until the buffer is full. At the same time the consumer can handle the messages at its own pace.

func UploadHandler(w http.ResponseWriter, r *http.Request) {
   if err := r.ParseMultipartForm(10 << 20); err != nil {
       http.Error(w, "Unable to parse form", http.StatusBadRequest)
       return
   }

   // create WaitGroup 
   var wg sync.WaitGroup 
   for _, file := range r.MultipartForm.File["files"] {
       f, err := file.Open()
       if err != nil {
          http.Error(w, "Unable to read file", http.StatusInternalServerError)
          return
       }

       wg.Add(1) // Add goroutine to the WaitGroup by incrementing the WaitGroup counter, this should be called before starting a goroutine
       // Process file concurrently
       go func(file multipart.File) {
           defer wg.Done() // decrement the counter by calling Done, utilize defer to guarantee that Done is called. 
           defer file.Close()
           processFile(f)
       }(f)
   }

   // Wait for all goroutines to complete
   wg.Wait()
   fmt.Fprintln(w, "All files processed successfully!")
}
Copy after login
Copy after login

In this example the producer can send up to two items without blocking. When the capacity of the buffer is reached the producer will block until the consumer handled at least one message.

Goroutines and Channels: Concurrency Patterns in Go

Back to the initial problem we want to limit the amount of goroutines processing files concurrently. To do this we can utilize buffered channels.

ch := make(chan int)
Copy after login

In this example we added a buffered channel with a capacity of 5, this allows us to process 5 files concurrently and limit strain on the system.

But what if not all files are equal? We might can reliably predict that different file types or file size require more resources to process. In this case we can utilize a weighted semaphore.

Weighted Semaphore

Simply put with a weighted semaphore we can assign more resources to a single tasks. Go already provides an implementation for a weighted semaphore within the extend sync package.

ch := make(chan int, 2)
Copy after login

In this version we created a weighted semaphore with 5 slots, if only images are uploaded for example the process handles 5 images concurrently, however if a PDF is uploaded 2 slots are acquired, which would reduce amount of files which can be handled concurrently.

Conclusion

We explored a few concurrency patterns in Go, utilizing sync.WaitGroup and semaphores to control the number of concurrent tasks. However there are more tools available, we could utilize channels to create a worker pool, add timeouts or use fan in/out pattern.
Additionally error handling is an important aspect which was mostly left out for simplicity.
One way to handle errors would be utilized channels to aggregate errors and handle them after all goroutines are done.

Go also provides a errgroup.Group which is related to sync.WaitGroups but adds handling of tasks which return errors.
The package can be found in the extend sync package.

The above is the detailed content of Goroutines and Channels: Concurrency Patterns in Go. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Golang's Impact: Speed, Efficiency, and Simplicity Golang's Impact: Speed, Efficiency, and Simplicity Apr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C   and Golang: When Performance is Crucial C and Golang: When Performance is Crucial Apr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

See all articles