

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Name:
Directions: Work only on this sheet (on both sides, if needed); do not turn in any supplementary sheets of paper. There is actually plenty of room for your answers, as long as you organize yourself BEFORE starting writing. Do not use any Python constructs which were not introduced either in lecture, discussion section or our written materials.
def cq(q):
i = atominc() ... i.inc()
would add 1 to i.val in an atomic manner.
print i.val
would print out the latest value stored (though of course it could be “old” by the time we get it).
We would still need to lock/unlock ourselves for operations other than incrementing. For instance, if we needed to perform some operations atomically if the stored value is 8, we’d write:
... i.lock() if i.val == 8: ... i.unlock()
Fill in the gaps below.
class atominc(): def init(self,initval): self.vallock = _______________ self.val = initval def inc(self):
def lock(self):
def unlock(self):
from s import * i = ints() for j in i: ... if j > 3: break
Then the execution of these statements will result in a total of iterators being created.
The variable ins will be such that ins[2], for instance, will initially consist of [x,y,2], where y is itrs[2] and x is the first element of the sequence produced by y.
Note that the built-in Python function min() does work lexicographically where appropriate; e.g. min([4,’abc’],[8,5],[3,200]) is [3,200].
Fill in the gaps. (In some cases it is possible to use fewer lines than allotted.)
def mrgitrs(itrs): tmp = [______________________________] ins = [______________________________] while ins != []: [val,itr,j] = min(ins) try:
except ______________________________:
import cq x = [5,12,8] c = cq.cq(x) c.next() 5 c.next()
12
c.next() 8 c.next() 5 x[1] = ’abc’ x [5, ’abc’, 8] c.next() 12 c.next() 8
Show how to remedy this problem by changing just one portion of one line in the original class.
Solutions:
def cq(q): while True: q[0:] = q[1:] + [q[0]] yield q[-1]
class atominc(): def init(self,initval): self.vallock = thread_allocate_lock() self.val = initval def inc(self): self.vallock.acquire() self.val += 1 self.vallock.release() def lock(self): self.vallock.acquire() def unlock(self): self.vallock.release()
setcheckinterval(5)