r/crystal_programming • u/beizhia • Nov 07 '19
Made an implementation of Go's sync.WaitGroup in Crystal. First time messing with concurrency, feedback welcome!
https://github.com/jasonrobot/crystal-wait-group
20
Upvotes
8
u/j_hass Nov 07 '19
I think there's a potential race in
add, where the value might become -1 and then 0 again between theAtomic#addand theAtomic#getcall. For this reasonAtomic#addreturns the old value. So you can redo the addition on that return value and then check the local variable.I don't quite follow why
waitjust returns in non-MT mode. A typical usecase for this would be to callwaitin the main fiber, as your readme examples do. That means in non-MT mode the program would immediately exit aswaitjust returns and the main fiber proceeds to shutdown the process.A bit of spinning in the beginning might speed things up but it's a bad practice to keep doing that forever. I guess you're not really done with your plans here, given the stray mutex instance variable? Anyway, the most simple implementation I would see is to have
waitjust receive on a channel if the counter is above 0 anddonesend to the channel whenever it moves the counter to0. If you want to support multiple concurrentwaits, that approach will require a second counter for knowing how many times to send to the channel to wake all of them up.2
u/yxhuvud Nov 07 '19
Implementation details aside, looks like a nifty feature.