Skip to main content

Concurrent Programming

Concurrent programming is about executing multiple computations simultaneously, managing parallelism and synchronization.

Core Concepts

Example: Go Goroutines

package main

import (
"fmt"
"time"
)

func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Printf("Worker %d processing job %d\n", id, j)
time.Sleep(time.Second)
results <- j * 2
}
}

func main() {
jobs := make(chan int, 100)
results := make(chan int, 100)

// Start 3 workers
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}

// Send jobs
for j := 1; j <= 5; j++ {
jobs <- j
}
close(jobs)

// Collect results
for a := 1; a <= 5; a++ {
<-results
}
}

Advantages

✅ Better resource utilization
✅ Improved responsiveness
✅ Scalability
✅ Performance gains

Use Cases

  • Web servers
  • Real-time systems
  • Parallel data processing
  • Distributed systems

🔀