Shared variables

Shared variables are accessible in all functions and to all turtles, regardless of which turtle created the variable and at which level of nested functions. Shared variables correspond to static variable known from other programming languages.
Use shared variables if a single copy of data should be available to all turtles. However, note: shared variables are browsed as the last, when a variable is not found among local and global variables. This makes the access to shared variables the least efficient.

Example 1:
Turtles in the program are monitoring value of the shared variable :s. A turtle terminates if it finds :s = true.

shared "s
"s := false

"t := newturtles 3 [
  let "tick timer [
    if :s [
      (print who "done)
      destroy
    ]
    (print who :iter)
  ] 300
]

wait 1500
print "stop
"s := true

Output:
Note: text outputs "name done" can appear not immediately after "stop" since between the print "stop instruction and "s := true other turtles can do their own instructions.

t2 1
t1 1
t3 1
t2 2
t1 2
t3 2
t2 3
t1 3
t3 3
t2 4
t1 4
t3 4
t2 5
t1 5
t3 5
t2 6
stop
t1 6
t3 6
t2 done
t1 done
t3 done

Example 2:
Code illustrates how to lock a variable for exclusive access. Functions take_some and return_all should be executed by a single turtle at a time in order to ensure that sum of the shared variable :tot and all the :my variables is constant. If lock is disabled (lines marked with stars are commented out) then the sum will vary randomly.
Also the sum is calculated inside the lock code block. This ensures that :tot and :my are not modified during the calculations.

to model
  to take_some
    if :tot > 0 [
      let "x (random :tot) + 1
      "tot -= :x
      "my += :x
    ]
  end

  to return_all
    "tot += :my
    "my := 0
  end

  "my := 0
  let "t timer [
    lock "tot [ ;******* change :tot value *********
      ifelse (random 2) = 0 [take_some] [return_all]
    ]           ;***********************************
  ] (random 10) + 1
end

shared "tot ;variable accessible to all turtles
"tot := 100

"t := newturtles 10 $model

"chk := timer [
  let "sum 0
  lock "tot [ ;*** sum up :tot and all :my ***
    foreach "ti :t ["sum += :my @ :ti]
    (print :sum + :tot :sum :tot)
  ]           ;*******************************
] 300

Output (version 1, no changes in the code):

100 100 0
100 11 89
100 76 24
100 72 28
100 79 21
100 76 24
...

Ourput (version 2, code with lock disabled):

100 100 0
195 168 27
290 288 2
75 40 35
70 43 27
6 6 0
...

See also:

Data types
Variables, data access
lock - execute instructions with exclusive access to a variable

Table of Content