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

Example

The program in Program Listing 3-8 illustrates Limbo threads:

Program Listing 3-8 threadx.b

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

The init function, Lines 11 through 18, creates a for loop that repeats five times, spawning the function func each time and printing the current iteration number. The function func also prints the iteration number passed to it by init. (The format flags added to the verb %d, 2 and 2.2, only serve to make it easier to distinguish which thread printed the number.)

The output from this program may look like this:

divine$ threadx
 1
   1
 2
   2
 3
 4
 5
   3
   4
divine$    5

The order of the output is indeterminate, depending on such external factors as system load, the number of processors, and system scheduling policy. If run this program multiple times, the order of the output would likely be different each time. The last line in the sample output shows that, in this case, the first thread, created when the program started in init, has exited and the prompt has returned before the last thread finishes.

The next section, Channels, shows how you can use channels to communicate between threads, including how to control thread synchronization with them.



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

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