[Contents]
[Prev] [Next] [Limbo Basics] [Limbo Programming] [Language Definition]

Simple Synchronization

The first example, Program Listing 3-9, uses channels for simple synchronization (refer to the example Program Listing 3-8 on page 3-32).

Program Listing 3-9 chanx.b

  1. implement Command;
  2. include "sys.m";
  3. include "draw.m";
  4. sys: Sys;
  5. print: import sys;
  6. sc: chan of int;
  7. rc: chan of int;
  8. Command: module {
  9. init: fn(ctxt: ref Draw->Context, argv: list of string);
  10. };
  11. init(ctxt: ref Draw->Context, argv: list of string) {
  12. sys = load Sys Sys->PATH;
  13. sc = chan of int;
  14. rc = chan of int;
  15. for (i:=1; i<=5; i++) {
  16. spawn func();
  17. print("%2d\n", i);
  18. sc<- = i;
  19. <-rc;
  20. }
  21. }
  22. func() {
  23. i := <-sc;
  24. print(" %2d\n", i);
  25. rc<- = i;
  26. }

The init thread initializes two channels that transport an integer. It then spawns a new thread with the function func. The new thread begins execution in func, where it blocks on the channel sc until a message arrives (Line 29). Meanwhile, the init thread continues to execute, printing the integer (Line 22) and sending the integer as a message on channel sc, before it blocks on the channel rc waiting for a return message (Line 24).

When func receives the message on channel sc, it continues to execute, printing the integer (Line 30) and sending the integer as a message on the channel rc, before it terminates.

When init receives the message on channel rc (it has blocked waiting for it on Line 24) it starts the next iteration of the for loop (Line 20) and the sequence starts over.



[Contents]
[Prev] [Next] [Limbo Basics] [Limbo Programming] [Language Definition]

Copyright © 1998, Lucent Technologies, Inc. All rights reserved.