Linda in Python
Posted 1 Oct 2004 by herman
Learn some of the Linda coordination language using Python.
The last part of the reading assignment on Parallel Programming describes Linda. A partial implementation of Linda, in python, is here: Linda.py. If you download this, you can write your own Linda programs and experiment. A test program using Linda is here: testLinda.py. The test program exercises Linda methods using Threads, to show how concurrent programs can coordinate and communicate using the Linda methods.
The basic theme of Linda is the notion of a "tuple space" that all parallel processes share. Initially, the tuple space is empty (unless you create it with some non-empty content). The tuple space is nothing more than a list of tuples.
The Out Method
Suppose a Linda tuplespace has been created, call it T. To add a tuple to T, we just executeT.Out(('a',5,1.2142))and this adds the tuple ('a',5,1.2142) into T. You can use any size tuple; examples could be (1,2), ('aaa','bbb','ccc'), (4,). That last example of (4,) is a tuple with just one item, and Python requires this peculiar syntax for singe-item tuples.
The same tuple can be added multiple times, as T is just a list, not a set.
The In Method
Suppose the Linda tuplespace T has these tuples:('a',5), ('b',3), ('c',12), ('b',20), ('a',5), ('d',0)Now if a program executes the assignmentr = T.In(('b',3))then the tuple ('b',3) will be removed from T, and r will be equal to ('b',3).
In can "wait"
For the same example of T above, suppose a program executes the assignmentr = T.In(('z',27))Obviously, this cannot succeed, because ('z',27) is not in T. But rather than fail or raise and exception, the In method will suspend execution and wait: it is waiting for some other Thread to add ('z',27) into tuplespace T. How long it will wait is your business, as programmer (to ensure there is some other Thread running that will add the needed tuple).
In can "wildcard"
For the same example of T above, suppose a program needs to search for a tuple, but only some of the tuple is known. The assignmentr = T.In(('b',None))attempts to remove some tuple from T whose first field is 'b'. As a result, r is ('b',3) or ('b',20), but we can't predict which will be assigned. What if there is no tuple with a first field of 'b'? Then the In method will wait for some other Thread to put a tuple with a first field 'b' into T.
The wildcarding is flexible. Here are valid examples of In:
The Rd Method
The Rd method of Linda is basically the same as In, except that it does not remove a tuple from the tuplespace. It can wait for a tuple, using wildcarding, and so on -- but it does not change the tuplespace.
The Inp Method
This is just like the In method, except that it does not wait in the case that no matching tuple is found. Instead, it raises a NameError exception.
The Rdp Method
Just like Rd, except that it does not wait when no matching tuple exists.