The next example is comprised of 3 files. The main program spawns a new thread with an external function (from a loaded module) and uses the same channel mechanism for communication between the threads.
Program Listing 3-10 is the main program.
Program Listing 3-10 chanx2a.b
implement Command;
include "sys.m";
include "draw.m";
include "chanx.m";
sys: Sys;
print: import sys;
cx: ChanX;
sc: chan of int;
rc: chan of int;
Command: module {
init: fn(ctxt: ref Draw->Context, argv: list of string);
};
init(ctxt: ref Draw->Context, argv: list of string) {
sys = load Sys Sys->PATH;
cx = load ChanX "./chanx2b.dis";
sc = chan of int;
rc = chan of int;
for (i:=1; i<=5; i++) {
spawn cx->func(sc, rc);
print("%2d\n", i);
sc<- = i;
func(<-rc);
}
}
func(i: int) {
print("%6d\n", i);
}
Program Listing 3-11, chanx2b.m, is the module interface file for Program Listing 3-12, chanx2b.b.
Program Listing 3-11 chanx2b.m
Program Listing 3-12 chanx2b.b
implement ChanX;
include "sys.m";
include "draw.m";
include "chanx.m";
sys: Sys;
print: import sys;
func(sc: chan of int, rc: chan of int) {
sys = load Sys Sys->PATH;
i: int;
i = <-sc;
print("%4d\n", i);
rc<- = i;
}