source: an embedded software primer 1ed by Simon
正确的code: https://ideone.com/pRhTMU
错误的code: https://ideone.com/M2ZRJB
很明显地可以看出这两段程式码的差别在于: 一个有用函式lSecondsSinceMidnight把变量
lSecondsToday包起来,一个是直接对变量lSecondsToday做access的动作。
这两段code都有用semaphore把lSecondsToday给包起来。
作者说第二种错误的方式会有bug,但,既然都已经用semaphore把lSecondsToday包起来了
,怎么会有bug的发生呢?为什么要多用一层lSecondsSinceMidnight把变量给包起来?
打到这里突然看到作者说的一段话:
At least some of bugs stem from undisciplined use: allowing code in many diffe-
rent modules to use the same semaphore and hoping that they all use it correct-
ly.
You can squash there bugs before they get crawling simply by hiding the semaph-
ore and the data that is protects inside of a module, thereby encapsulating bo-
th.
作者说把semaphore与semaphore要保护的data放在module里可以防止"code in many diff-
erent modules to use the same semaphore".
但...在第一种正确的方式,function vHackerTask与vJuniorProgrammerTask都呼叫同一
个function lSecondsSinceMidnight,不也是"use the same semaphore"吗?
想请教各位前辈是不是我误会了什么?谢谢