Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Task: per host concurrency limits for web crawler (map[string]Semaphore).

I considered chan struct{} (chan bool) approach, but essentially it would not make code a lot easier because the main hurdle is to delete unused keys from map. And then semaphore takes constant memory - good property - as opposed to chan which grows with each "acquired limit".

I started with Semaphore using sync. Cond Wait/Signal (desired behavior of semaphore is well described in comments). Then I created map[string]*Semaphore with Mutex around all map operations and after semaphore is on hands, Acquire/Release it - that would block caller if needed but not block other access to map.

To remove unused semaphores from map I use separate counter that is stored in semaphore struct and modified only inside map lock. Its value sometimes differs from semaphore.value. When this counter goes to zero I know there are no goroutines that have pointer to semaphore from map except maybe one that is going to do final Release() now, so it's safe to delete key from map to preserve memory.

Essentially it works, test passes, but I would really appreciate any feedback on this approach.

Code link:

// Package limitmap provides map of semaphores to limit concurrency against some string keys.
// Usage:
// limits := NewLimitMap()
// func process(url *url.URL, rch chan *http.Response) {
//   // At most 2 concurrent requests to each host.
//   limits.Acquire(url.Host, 2)
//   defer limits.Release(url.Host)
//   r, err := http.Get(url.String())
//   rch <- r
// }
// for url := range urlChan {
//   go process(url, rch)
// }

package limitmap

import (

// Internal structure, may be changed.
// Requirements for this data structure:
// * Acquire() will not block until internal counter reaches set maximum number
// * Release() will decrement internal counter and wake up one goroutine blocked on Acquire().
//   Calling Release() when internal counter is zero is programming error, panic.
type Semaphore struct {
    // Number of Acquires - Releases. When this goes to zero, this structure is removed from map.
    // Only updated inside lock.
    refs int

    max   uint
    value uint
    wait  sync.Cond

func NewSemaphore(max uint) *Semaphore {
    return &Semaphore{
        max:  max,
        wait: sync.Cond{L: new(sync.Mutex)},

func (s *Semaphore) Acquire() uint {
    defer s.wait.L.Unlock()
    for i := 0; ; i++ {
        if uint(s.value)+1 <= s.max {
            return s.value
    panic("Unexpected branch")

func (s *Semaphore) Release() (result uint) {
    defer s.wait.L.Unlock()
    if s.value < 0 {
        panic("Semaphore Release without Acquire")

type LimitMap struct {
    lk     sync.Mutex
    limits map[string]*Semaphore
    wg     sync.WaitGroup

func NewLimitMap() *LimitMap {
    return &LimitMap{
        limits: make(map[string]*Semaphore),

func (m *LimitMap) Acquire(key string, max uint) {
    l, ok := m.limits[key]
    if !ok {
        l = NewSemaphore(max)
        m.limits[key] = l

    if x := l.Acquire(); x < 0 || x > l.max {

func (m *LimitMap) Release(key string) {
    l, ok := m.limits[key]
    if !ok {
        panic("LimitMap: key not in map. Possible reason: Release without Acquire.")
    if l.refs < 0 {
        panic("LimitMap internal error: refs < 0.")
    if l.refs == 0 {
        delete(m.limits, key)

    if x := l.Release(); x < 0 || x > l.max {

// Wait until all released.
func (m *LimitMap) Wait() {

func (m *LimitMap) Size() (keys int, total int) {
    keys = len(m.limits)
    for _, l := range m.limits {
        total += int(l.value)
share|improve this question

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.