Thursday, January 23, 2014


I'm happy to say that Crack now supports threading.  Thread support required two basic ingredients: a pthread extension (wrapped in a high-level Crack module) and the atomic_int type for reference counting.

Normal integer operations are not sufficient to support reference counting in a multithreaded environment.  Compilers and CPUs perform all kinds of tricks in order to improve performance, and this can result in two different threads seeing two different values for the same variable at any given point in time.  Atomic operations solve this problem.  They prevent the compiler from doing any special tricks to elide or reorder the operation, and require the CPU to lock the bus and synchronize the operation across all views of memory.

To expose atomic operations in the language, I've created an atomic_int type which supports a limited set of integer operations (mainly += and -=) and synchronized conversion to plain integer types.  The reference count of crack.lang.Object is now of type atomic_int, giving us atomic reference counts.

For actual thread creation and more general synchronization, I've implemented the crack.threads module.  This provides Crack classes encapsulating functions from a new pthread extension, so we have Thread, Mutex and Condition classes.  There is also a higher level Queue generic which provides one of the most common modes of inter-thread communication.

The new threading code is currently available only from the repository, but we're about due for a release, so it should be available soon in version 0.9 of the crack SDK.