Skip to content

Unbounded Concurrency

Johnny Boursiquot edited this page May 31, 2024 · 1 revision

Go's concurrency capabilities are great but with great power comes great responsibility (you probably saw that one coming 😄). In certain cases, unmanaged concurrency can create some unexpected results in your programs, especially when the things your programs interact with have constraints of their own which in turn impact your implementation.

Consider the following sample solution for the previous excercise:

e1-synchronized/main.go

...

func main() {
    ...

	var wg sync.WaitGroup
	wg.Add(tp - fp + 1) // +1 to avoid an off by one issue
	for i := fp; i <= tp; i++ {
		go func(p int) {
			defer wg.Done()
			conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", host, p))
			if err != nil {
				log.Printf("%d CLOSED (%s)\n", p, err)
				return
			}
			conn.Close()
			log.Printf("%d OPEN\n", p)
		}(i)
	}
	wg.Wait()
}

Let's introduce a real-world constraint on the program using ulimit. We'll limit the number of allowed file descriptors available to the program which in turn limits the number of network connections it can open.

$ ulimit -n 100; go run ./e1-synchronized/*.go -from=8000 -to=9000
2024/05/31 02:20:00 8009 CLOSED (dial tcp 127.0.0.1:8009: connect: connection refused)
2024/05/31 02:20:00 8178 CLOSED (dial tcp 127.0.0.1:8178: socket: too many open files)
2024/05/31 02:20:00 8277 CLOSED (dial tcp 127.0.0.1:8277: socket: too many open files)
2024/05/31 02:20:00 8179 CLOSED (dial tcp 127.0.0.1:8179: socket: too many open files)
2024/05/31 02:20:00 8254 CLOSED (dial tcp 127.0.0.1:8254: connect: connection refused)
2024/05/31 02:20:00 8107 CLOSED (dial tcp 127.0.0.1:8107: socket: too many open files)
2024/05/31 02:20:00 8180 CLOSED (dial tcp 127.0.0.1:8180: socket: too many open files)
2024/05/31 02:20:00 8279 CLOSED (dial tcp 127.0.0.1:8279: socket: too many open files)
2024/05/31 02:20:00 8136 CLOSED (dial tcp 127.0.0.1:8136: socket: too many open files)
2024/05/31 02:20:00 8181 CLOSED (dial tcp 127.0.0.1:8181: socket: too many open files)
2024/05/31 02:20:00 8948 CLOSED (dial tcp 127.0.0.1:8948: connect: connection refused)
2024/05/31 02:20:00 8080 CLOSED (dial tcp 127.0.0.1:8080: socket: too many open files)

As we iterate over the range of ports fed in by the end-user, we eventually run into a system constraint, creating an "unbounded concurrency" problem. While it's tempting to seek a change in the environment our programs run in, we often do not have such control and instead must adapt our programs.

Discussion

  • Can you think of a resource-constraint problem you're actively dealing with?

Resources

Clone this wiki locally