对比左右2个程序:
Rather small syntactical differences:
• package is replaced by protected for the module which encapsu-
late the data (Store) which potentially needs protection.
• Some of the procedures are replaced by entries.
On the right side, the keyword protected as well as the specific structure around the entry definitions provide a set of rules which restrict access to those operations under certain conditions:
- procedures enforce mutual exclusion with all other operations in the same protected object.
- entries enforce the same constraints as procedures, yet are also associated with a guard (boolean expression) which needs to be ful lled before a task is allowed to enter (otherwise it is blocked and neatly queued up until the guard opens up again)
- functions are side-effect free with respect to the protected data, i.e. the compiler will treat any write access to the protected data from within a protected function as an error.
In short: there can only ever be maximally one task inside a protected object if this task entered via a protected procedure or entry. Alternatively, multiple tasks can use one or multiple protected functions concurrently.
protected object 就像是一个特殊数据结构,被各种task取用或者调用。
练习
- What will happen if you exchange the two inner for-loops (if anything)?
After we exchange their positions, protected objects are executed in front of unprotected object and different task will finish the first loop at different time spots due to the protected entry. So most of interleaves on “store” can be avoided
- What will happen if you increment both values in the same for-loop (if anything)?
After I put 2 ‘inc’ in the same loop, every tasks will be executed one by one in “Protected_Element.Inc”, which means that all tasks will be released from “Protected_Element.Inc” at different time spot in each iteration. Therefore, the possibility of operating on the same unprotect resource is limited
- What will happen if you count only to 10 inside each task (if anything)?
After I modified ‘count only to 10 inside each task’, because there are 10 tasks and the count is 10, all the output is 10*10 = 100. Although, the mutual exclusion is not guaranteed in unprotected object, but as the count is quite small --- only 10, the interleave occurs rarely.