I have this really simple JCSP(Java Communicating Sequential Processes) code sample in which I'm trying to write an integer to a One2OneInt channel and then read it.
package jcsp;
import org.jcsp.lang.*;
public class JCSP {
public static void main(String[] args) {
One2OneChannelInt chan = Channel.one2oneInt();
chan.out().write(5);
System.out.println("Written...");
System.out.println(chan.in().read());
}
}
It seems that value never gets written on the channel and program just keeps running. "Written..." is never printed out.
So I learned about BlockingQueue and its implementation SynchronousQueue. As stated here, SynchronousQueue works in similar way in which CSP Channels work. This helped me realize what was wrong with my code. Simply put, you can't write and read from channel in same process. Channel is way for processes to communicate.
Similarly to SynchronousQueue's put() which will wait for other process to call take(), CSP Channel's write() which will wait for corresponding read() to be called. The difference is that CSP Channels have objects ChannelOutput and ChannelInput through which objects are written and red. Conversely, you can call put and take directly on instance of SynchronousQueue. Personally, I find SynchronousQueue much easier to understand, which probably relates to JCSP not being very popular.
Still, if you're interested how I made the above code work in JCSP, here it is:
public static class Process1 implements CSProcess {
private ChannelOutputInt output;
public Process1(ChannelOutputInt out) {
output = out;
}
@Override
public void run() {
for (int i = 0; i < 1; i++) {
System.out.println("Written...");
output.write(5);
}
output.write(-1);
}
}
public static class Process2 implements CSProcess {
private ChannelInputInt input;
public Process2(ChannelInputInt in) {
input = in;
}
@Override
public void run() {
int x = 0;
while ((x = input.read()) > 0) {
System.out.println(x);
}
}
}
public static void main(String[] args) {
One2OneChannelInt chan = Channel.one2oneInt();
Process1 process1 = new Process1(chan.out());
Process2 process2 = new Process2(chan.in());
Parallel parallel = new Parallel();
parallel.addProcess(process1);
parallel.addProcess(process2);
parallel.run();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With