## digitalmars.D - Re: DMD 1.022 and 2.005 DCSP solution

• Mikola Lysenko (47/51) Oct 07 2007 Well, here's how you would do a bounded buffer in DCSP (D Communicating ...
```David Brown Wrote:

I'll give an inverse challenge (which I'm going to try and meet, see
below): Implement a standard threading problem, such as bounded buffers
using only the Phobos thread primitives.  The solution may not use anything

Well, here's how you would do a bounded buffer in DCSP (D Communicating
Sequential Processes):

void boundedBuffer(T, int B)
(
WriteChannel!(T) get,
lazy bool done
)
{
size_t pos = 0;
T[] buffer = new T[B];

while(!done())
{
alternative(
guard(pos > 0 && get.write(buffer[pos-1]), { pos--; }),
guard(pos < B && put.read(buffer[pos]), { pos++; }),
done()
);
}
}

Which you could then use in the following way:

auto get = new Channel!(int);
auto put = new Channel!(int);

bool done = false;

parallel(
boundedBuffer!(int, 10)(get, put, done),
{
for(int i=0; i<100; i++)
{
put.write(i);
writefln("writing %s", i);
}
},
{
for(int i=0; i<100; i++)
{
int x;
}

done = true;
});

A few quick notes about DCSP:  First, it is not anywhere near a finished
product, which means that it would be ill advised to consider using it for
anything practical.  Next, it is inspired largely by process calculi which use
point-to-point channels for communication.  That means that processes block on
both reads and writes on when they communicate.

The alternative statement in this code is also a bit tricky.  It basically
forces the code to wait until one of the guarded conditions is true.  After
which, it executes the code in the body of the condition.  Guarded conditions
can be boolean expressions, channel read/writes, or barrier synchronization.
Only one guarded condition is carried out per alt block.  If no condition is
satisfied, the process waits.

There are several theoretical advantages to this approach, most notably it
makes it possible to use certain results from type theory to prove the