←back to thread

Go subtleties

(harrisoncramer.me)
234 points darccio | 4 comments | | HN request time: 0.703s | source
1. tonymet ◴[] No.45670710[source]
my favorite go trick is a simple semaphore using make(chan struct{}, CONCURRENCY) to throttle REST api calls and other concurrent goroutines.

It’s really elegant acquisition by reading, and releasing the semaphore by writing.

Great to limit your rest / http crawlers to 8 concurrent calls like a web browser.

replies(1): >>45676618 #
2. sa46 ◴[] No.45676618[source]
Why not use the standard-library adjacent semaphore package?

One problem with using a channel as a semaphore is you need to track if you've closed the channel when "releasing".

https://pkg.go.dev/golang.org/x/sync/semaphore#Weighted.Acqu...

replies(2): >>45678159 #>>45678779 #
3. tonymet ◴[] No.45678159[source]
I don’t like libs
4. themafia ◴[] No.45678779[source]
> is you need to track if you've closed the channel

There is where you can use a function that captures the channel and guarantees that no matter how many times it is called that it only closes the channel once.