alitto / pond

🔘 Minimalistic and High-performance goroutine worker pool written in Go
MIT License
1.43k stars 60 forks source link

Why use atomic.AddInt32() and sync.Mutex at the same time #18

Closed zhu121 closed 2 years ago

zhu121 commented 2 years ago

File:pond.go Function:decrementWorkerCount() and incrementWorkerCount() Question: In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The AddInt32() function in Golang is used to atomically add delta to the *addr. In addition, using the sync.Mutex to ensure the mutually exclusive execution of a piece of code. Aren't these two equivalent?

alitto commented 2 years ago

Hey @zhu121,

The reason the mutex lock is needed there is to prevent decrementWorkerCount decreasing the workerCount variable while this block is executed in incrementWorkerCount, which could bring undesirable consequences, such as adding more workers than necessary or not starting new ones when needed. And for this to happen, the runningWorkerCount variable in that block must reflect the actual number of worker goroutines during the entirety of the block. A similar thing could happen if incrementWorkerCount was executed simultaneously from 2 different threads. Does it make sense?

zhu121 commented 2 years ago

Hey @zhu121,

The reason the mutex lock is needed there is to prevent decrementWorkerCount decreasing the workerCount variable while this block is executed in incrementWorkerCount, which could bring undesirable consequences, such as adding more workers than necessary or not starting new ones when needed. And for this to happen, the runningWorkerCount variable in that block must reflect the actual number of worker goroutines during the entirety of the block. A similar thing could happen if incrementWorkerCount was executed simultaneously from 2 different threads. Does it make sense?

Hey @alitto, thank you for your reply, I understand it