Saturday, March 28, 2009

D for Programmers

I wrote a while ago about implementing thread support in the D .net compiler. The idea was to generate code that constructs delegates that are passed to the Start method of the System.Threading.Thread class. I discussed some details of constructing delegates out of nested functions, and I concluded that my next thread-related task was to implement support for the synchronized keyword.

Like the postman who goes for a walk in the park after coming home from work, I relax in the after hours by working on pet projects like C++ debuggers and D compilers. So this Saturday morning I sat down to implement the code generation for synchronized. The D language accepts two statement forms:
synchronized ScopeStatement
synchronized (Expression) ScopeStatement
The former can be easily reduced to the latter by synthesizing a global object and an expression that references it.

Here is a sample of D code that illustrates the use of the synchronized keyword:

import System;

class Semaphore {
bool go;
}
Semaphore sem = new Semaphore;

void main() {
void asyncWork() {
while (true) { // busy wait
synchronized(sem) {
if (sem.go) break;
}
}
}
Threading.Thread t = new Threading.Thread(&asyncWork);
t.Start();
synchronized(sem) {
sem.go = true;
}
t.Join();
}
A synchronized statement can be transformed into the following pseudo-code:
object m = Expression();
try {
lock(m);
ScopeStatement();
}
finally {
unlock(m);
}
Implementing lock / unlock maps naturally to the Enter / Exit methods of the System.Threading.Monitor class. That's really all there is to it, generating the method calls is trivial.

I was a bit disappointed by how easy the task turned out to be, but on the bright side I had plenty of time left to spend with my kid. I took him to Barnes and Noble to check out the Thomas trains and board books and the computer section, where I found the most helpful book title ever: "C# for Programmers". I guess no lawyer accidentally wandering through the computer book section can claim that he bought the book because the title was misleading. I wish that all book titles be so clear: "Finance for Accountants" or "Elmo Board Book for Toddlers".

No comments: