作者zzss2003 (brotherD)
看板C_and_CPP
标题[问题] encapsulation的应用(C)
时间Fri Jun 29 11:58:32 2018
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"吗?
想请教各位前辈是不是我误会了什麽?谢谢
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 61.216.85.243
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1530244718.A.D72.html
1F:→ bluesoul: 第二段code回圈的部分没有保护 06/29 12:06
有,回圈上有comment,有说hope junior remembers to use the semaphore
2F:→ sarafciel: 他那段话不是在否定use the same of semaphore这件事 06/29 13:20
3F:→ sarafciel: 简单的讲就是 你不知道用你的code的人是雷包还是大师 06/29 13:23
4F:→ sarafciel: 那麽让他们去写semaphore 你也不知道他们写得对不对 06/29 13:26
5F:→ sarafciel: 还不如你自己实作正确的同步函式给他们call比较好 06/29 13:26
6F:→ sarafciel: 讲同步不太精确....应该说可平行化 06/29 13:28
其实我认为这段不是在表达这个意思。GetSemaphore与GiveSemaphore都是厂商提供的fun-
ction,作者是站在"function的使用者"的角度去表达这段话
※ 编辑: zzss2003 (60.251.49.183), 06/29/2018 17:59:39
7F:→ sarafciel: "hope junior remembers" 你怎麽会理解成他有保护.... 06/30 13:51
8F:→ sarafciel: 他里面那三个.c档 是不同的人在写的code 06/30 13:55
9F:→ sarafciel: 第一个vtimertask()只是跟你示意说lSecondsToday需要被 06/30 13:59
10F:→ sarafciel: 保护 所以後面hacker跟junior这两个想使用它的时候 06/30 14:01
11F:→ sarafciel: 应该也要用semphore保护 问题是他不知道hacker跟junor 06/30 14:02
12F:→ sarafciel: 他们会不会加 或着是写一写忘记这个变数是该被保护的结 06/30 14:04
13F:→ sarafciel: 果没加 那最保险的做法就是他们要用的时候封装成一个 06/30 14:04
14F:→ sarafciel: function去保护变数 06/30 14:08
15F:→ sarafciel: 至於use the same semaphore 我换个角度跟你讲 06/30 14:11
16F:→ sarafciel: 我把变数包起来 跟把整个回圈 甚至整个main包起来 06/30 14:15
17F:→ sarafciel: 这些也都是use the same semaphore 问题是後面两个 06/30 14:17
18F:→ sarafciel: 会把semaphore拿着太久 造成其他thread不必要的等待 06/30 14:18
谢谢你的解释,我不懂的原因是因为我卡在这句英文:
At least some of those bugs stem from undisciplined use: allowing code in many
different modules to use the same semaphore and hoping that they all use it
correctly.
我一开始把"允许不同module内的code使用一样的semaphore"认为是undisciplined use,
仔细看了一遍,原来作者的意思是"允许不同module内的code使用一样的semaphore,且希
望他们正确地使用"这一整段话才是undisciplined use。
※ 编辑: zzss2003 (60.251.49.183), 07/02/2018 13:59:34