Hi All,
I've created this small piece of code (that I can't test yet) to provide the
preemptive multitasking with stackless python that Chris is currently working
on.
Comments/hints are very welcome:
(file: preemptive.py)
#!/usr/bin/python
'''Provide tools for preemptive multitasking with stackless python.
Actual scheduling/locking is performed by communicating over (stackless')
channels.
The goal here is to set the atomic flag for a short a period as possible.
Author: Eric van Riet Paap <eric at vanrietpaap.com>'''
import stackless
class mutex:
'''mutual exclusion object'''
data = {}
def __init__(self, name):
'''mutexes are initialy unlocked'''
self.name = name
if not self.channel.has_key(name):
self.data[name] = [0, stackless.channel()]
def isLocked(self):
'''return non-zero if locked'''
return self.data[self.name][0]
def lock(self):
'''acquire the lock'''
a = stackless.setatomic(1)
n, ch = self.data[self.name]
self.data[self.name][0] = n+1
if n: #other tasklet acquired the mutex
#note: we actually might need to setatomic(0) here,
however I'm a bit afraid of switches that
# might happen between setatomic(0) and the next
line! (Chris, what do you think?)
ch.receive() #wait for tasklet with lock to send
data
stackless.setatomic(a)
def unlock(self):
'''release the lock'''
a = stackless.setatomic(1)
n, ch = self.data[self.name]
self.data[self.name][0] = n-1
if n: #other tasklets would like to aqcuire the mutex
#note: same note is with lock method.
ch.send(n) #wake up a tasklets that is trying to
receive data from this channel
stackless.setatomic(a)
_______________________________________________
Stackless mailing list
Stackless at www.tismer.comhttp://www.tismer.com/mailman/listinfo/stackless