Are variables thread safe in sclang?

for the most part, yes. you have the guarantee that almost all operations at the bytecode level are atomic. this includes loading and storing the value of a variable, which is what you mean by “safe access”, i think.

however, you are responsible for making your own code thread safe in a multithreaded environment. for example, if your code yields in the middle of a set of operations that ought to be atomic, perhaps by calling some externally supplied function, your code is no longer thread safe. the next scheduled thread would see a partially executed “atomic” transaction. it is still possible to come up with race conditions in SuperCollider, they are just not of the classic, “two threads loading and storing an int in a loop”, variety.

a concrete example:

// Wrapper around some object that also stores its
// size, calculated once in case it is expensive.
// User code can also set a function to be called when
// the size changes.
MyStorage {
  var <size = 0, <>onSizeUpdate, <storedObject;

  setStored { |newStored|
    var newSize = newStored.size;
    if (size != newSize) {
      onSizeUpdate.value()
      // This call could yield(). Another thread may
      // then observe this object and find that its size is
      // not the same as storedObject.size, breaking
      // thread safety.
    };
    storedObject = newStorage;
  }
}
2 Likes