IntroductionPyCSP provides an API that can be used to write concurrent applications using CSP (Communicating Sequential Processes). The API is implemented in four versions: Threads, processes, greenlets and net. All implementations share an almost identical API making it trivial to switch from one implementation to another.
Requirements:
ContentsInstallingStart by fetching the latest tarball. Unpack and to install run python setup.py install You can now try starting your python interpreter and type import pycsp. If no errors, then you are good to go. The default implementation is always pycsp.threads. >>> import pycsp >>> print pycsp.version (0, 7, 1, 'threads') Elements of PyCSPOpen a new file and put from pycsp.threads import * as your first line. ProcessesThis is a process with one output channel end: @process
def counter(cout, limit=1000)
for i in xrange(limit):
cout(i)To start two instances of our newly created counter process we have the following options. In parallelThe Parallel construct will block until both counter processes have terminated. Parallel(counter(...), counter(...)) They can also be started asynchronously by using the Spawn construct. Spawn(counter(...), counter(...)) In sequenceThe Sequence construct will block until both counter processes have terminated. Only one process will be execute at any possible time and will be executed in the order they are provided. Sequence(counter(...), counter(...)) Channels and channel endsChannels can have any number of readers and writers and will block until a read or write have been committed to the opposite action. A = Channel('A')To communicate on a channel you are required to join it first. cin = A.reader() or cout = A.writer() A Simple Application@process
def counter(cout, limit):
for i in xrange(limit):
cout(i)
poison(cout)
@process
def printer(cin):
while True:
print cin(),
A = Channel('A')
Parallel(
counter(A.writer(), limit=10),
printer(A.reader())
)Output: 0 1 2 3 4 5 6 7 8 9 More ExamplesFor a lot more examples. | |