Created
March 28, 2025 09:02
-
-
Save dacr/d2cac034694c8cb61c24f4c9f3443cf9 to your computer and use it in GitHub Desktop.
go routines mutex / published by https://github.com/dacr/code-examples-manager #e4bc0bea-e40e-4039-b5d1-e45d788d387e/f710e9e2878711664f63beb2323f792892ffd7c3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*?sr/bin/true; exec /usr/bin/env nix-shell -p go --run "go run $0" #*/ | |
// summary : go routines mutex | |
// keywords : go, goroutines, mutex, @testable | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : e4bc0bea-e40e-4039-b5d1-e45d788d387e | |
// created-on : 2025-03-27T15:17:01+01:00 | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : nix-shell -p go --run "go run $file" | |
package main | |
import ( | |
"sync" | |
) | |
func main() { | |
sg := sync.WaitGroup{} | |
mutex := sync.Mutex{} | |
list := []int{} | |
for i := range 100 { | |
sg.Add(1) | |
go func() { | |
defer sg.Done() | |
mutex.Lock() // ************ to avoid concurrent access | |
if len(list) < 20 { | |
list = append(list, i) | |
} | |
mutex.Unlock() // ************ | |
}() | |
} | |
sg.Wait() | |
for i, winner := range list { | |
println(i, winner) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment