Last active
February 3, 2026 20:27
-
-
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/ce3bbb22a4fb3640c4f47defe331b967d1a257f7
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 License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // 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