RSS DEV Community

Implement semaphore in golang by buffered channel

The code demonstrates a semaphore implementation in Go using a buffered channel. The semaphore is created with a capacity of 10, allowing a maximum of 10 concurrent processes. The main function iterates 1000 times, sending an integer to the semaphore channel in each iteration. If the channel is full, the loop is blocked until a value is released from the channel. A new goroutine is started for each iteration, which prints a start message and then sleeps for a random duration between 0 and 20 seconds. When the goroutine finishes, it releases a value from the semaphore channel, making it available for the next iteration. The release of the value is done using the `<- sem` statement, which also retrieves the original value sent to the channel. The program prints start and end messages for each process, including the process ID and the duration it took to complete. The output shows that the processes are executed concurrently, with a maximum of 10 processes running at the same time. The program uses the `time` and `math/rand` packages to introduce randomness in the sleep duration.
dev.to
dev.to
Implement semaphore in golang by buffered channel
Create attached notes ...