Commit d7521118 authored by Amos Latteier's avatar Amos Latteier

changed callback mechanism to make it more flexible, also added callback

on close().
parent e4ec8395
......@@ -7,8 +7,12 @@ from string import join
TupleType=type(())
class OutputPipe:
"""A pipe which can be written to and read from different threads.
Also supports callbacks to notify readers when the pipe has been
written to or has been closed."""
def __init__(self,callback=None):
"callback should be a tuple (function,(args,))"
lock=thread.allocate_lock()
self._r=lock.release
self._a=lock.acquire
......@@ -20,7 +24,15 @@ class OutputPipe:
try:
self._buf.append(text)
finally: self._r()
Wakeup(self._callback)
self.notify()
def notify(self):
if self._callback:
fun=self._callback[0]
args=self._callback[1]+(self,)
Wakeup(lambda f=fun,a=args: apply(f,a))
else:
Wakeup()
def close(self):
self._a()
......@@ -29,6 +41,7 @@ class OutputPipe:
if b: self._buf=tuple(b)
else: self._buf=None
finally: self._r()
self.notify()
def read(self):
"""Read data from the pipe
......@@ -36,7 +49,6 @@ class OutputPipe:
Return None if the pipe is open but has no data.
Return an empty string if the pipe is closed.
"""
print "read from pipe"
self._a()
try:
b=self._buf
......
......@@ -7,8 +7,12 @@ from string import join
TupleType=type(())
class OutputPipe:
"""A pipe which can be written to and read from different threads.
Also supports callbacks to notify readers when the pipe has been
written to or has been closed."""
def __init__(self,callback=None):
"callback should be a tuple (function,(args,))"
lock=thread.allocate_lock()
self._r=lock.release
self._a=lock.acquire
......@@ -20,7 +24,15 @@ class OutputPipe:
try:
self._buf.append(text)
finally: self._r()
Wakeup(self._callback)
self.notify()
def notify(self):
if self._callback:
fun=self._callback[0]
args=self._callback[1]+(self,)
Wakeup(lambda f=fun,a=args: apply(f,a))
else:
Wakeup()
def close(self):
self._a()
......@@ -29,6 +41,7 @@ class OutputPipe:
if b: self._buf=tuple(b)
else: self._buf=None
finally: self._r()
self.notify()
def read(self):
"""Read data from the pipe
......@@ -36,7 +49,6 @@ class OutputPipe:
Return None if the pipe is open but has no data.
Return an empty string if the pipe is closed.
"""
print "read from pipe"
self._a()
try:
b=self._buf
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment