Skip to content

Instantly share code, notes, and snippets.

@axiaoxin
Created December 17, 2018 03:23
Show Gist options
  • Save axiaoxin/573ffd3609beb94a424e540d003e70fb to your computer and use it in GitHub Desktop.
Save axiaoxin/573ffd3609beb94a424e540d003e70fb to your computer and use it in GitHub Desktop.
Ways to limit concurrent resource use
package main
import (
"log"
"sync"
"time"
)
func main() {
log.SetFlags(log.Ltime)
var wg sync.WaitGroup
var mu sync.Mutex
for i := 0; i < 9; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
mu.Lock()
defer mu.Unlock()
// Resource intensive work goes here
time.Sleep(time.Second)
log.Println(i)
}(i)
}
wg.Wait()
}
package main
import (
"log"
"sync"
"time"
)
func main() {
log.SetFlags(log.Ltime)
tasks := make(chan int)
var wg sync.WaitGroup
for worker := 0; worker < 3; worker++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := range tasks {
// Resource intensive work goes here
time.Sleep(time.Second)
log.Println(i)
}
}()
}
for i := 0; i < 9; i++ {
tasks <- i
}
close(tasks)
wg.Wait()
}
package main
import (
"log"
"sync"
"time"
)
func main() {
log.SetFlags(log.Ltime)
var wg sync.WaitGroup
var mu sync.RWMutex
for i := 0; i < 9; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
if i == 4 {
mu.Lock()
defer mu.Unlock()
} else {
mu.RLock()
defer mu.RUnlock()
}
// Resource intensive work goes here
time.Sleep(time.Second)
log.Println(i)
}(i)
}
wg.Wait()
}
package main
import (
"log"
"sync"
"time"
)
func main() {
log.SetFlags(log.Ltime)
var wg sync.WaitGroup
semaphore := make(chan struct{}, 3)
for i := 0; i < 9; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
semaphore <- struct{}{} // Lock
defer func() {
<-semaphore // Unlock
}()
// Resource intensive work goes here
time.Sleep(time.Second)
log.Println(i)
}(i)
}
wg.Wait()
}
package main
import (
"log"
"sync"
"time"
)
func main() {
log.SetFlags(log.Ltime)
var wg sync.WaitGroup
for i := 0; i < 9; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
// Resource intensive work goes here
time.Sleep(time.Second)
log.Println(i)
}(i)
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment