[问题] encapsulation的应用(C)

楼主: zzss2003 (brotherD)   2018-06-29 11:58:32
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"吗?
想请教各位前辈是不是我误会了什么?谢谢
作者: bluesoul (忙死你老爸)   2018-06-29 12:06:00
第二段code循环的部分没有保护
作者: sarafciel (Cattuz)   2018-06-29 13:20:00
他那段话不是在否定use the same of semaphore这件事简单的讲就是 你不知道用你的code的人是雷包还是大师那么让他们去写semaphore 你也不知道他们写得对不对还不如你自己实作正确的同步函式给他们call比较好讲同步不太精确....应该说可平行化

Links booklink

Contact Us: admin [ a t ] ucptt.com