When I was taking a compilers course, I noticed the grammars for C/C++/Java etc. allow for blocks with no conditional or function signature at the top. I couldn’t think of what this would be used for except to make the grammar easier to describe. Later, while writing code with lots of mutual exclusion, my code was getting hard to read. My friend Logan suggested if most mutexes are small blocks of code, why not use braces to denote them? Here’s what it looks like:
sema_wait(&shared->mutex);
{
memcpy(result, current_call->result,
sizeof(RPCResult));
ret = current_call->retStatus;
current_call->next = shared->available;
shared->available = current_call_index;
}
sema_post(&shared->mutex);
Emacs also nicely indents the blocks which really extends the readability.
As Dan has pointed out, even though the braces are being used as a visual indicator to the programmer, the braced sections are still semantically treated as blocks by the compiler; meaning a new scope is created. This is not necessarily a negative, however, because a lot of the time the new scope can make sense (similar to mutexing an entire function) or, at the very least, not hurt. Dealing with the new scope is as simple as dealing with the new scope of a for-loop. If you are writing threaded code, I hope you can deal with semantic blocks.
- None Found