Question

I took it upon myself recently to work towards making a general-purpose Translator to automatically translate js programs into C, but I got stuck when thinking of asynchronous behaviour. Using ANSI / POSIX C, and only allowing yourself to use a library for a threadpool implementation, how would you go about implementing asynchronous function calls in C. The methodology must be thread-safe. When I came up with my approach, I was inspired by this source's use of what they call the Asynchronous Dispatcher pattern: https://doanduyhai.wordpress.com/2012/08/04/design-pattern-the-asynchronous-dispatcher/

Was it helpful?

Solution

Are you aiming at making a general-purpose Javascript to C automatic translator (that is, a compiler from Javascript to C)?

This is quite challenging and will take you several years of work, in particular if you want to make an efficient Javascript to C compiler (something which won't be much slower than most current Javascript implementations)

Notice that semantically Javascript has a lot of common features with Scheme (dynamic typing, garbage collection, closures, and perhaps run-time evaluation), even if the syntax is very different. Its prototype object model is indeed not in Scheme, but you could find some implementations of prototype object models in Scheme quite similar to the Javascript model. So I definitely recommend studing Scheme and its formal semantics, and looking inside several Scheme to C translators (Bigloo, Chicken, Stalin, ...). In contrast to Scheme, Javascript was initially ill-defined (its first implementation was a few weeks hack!) and has some unpleasant peculiarities (result of [] + {}, etc...) that are painful to handle in a Javascript to C translator.

Then I strongly recommend reading C.Queinnec Lisp In Small Pieces book. Read also Scott's programming language pragmatics book.

The asynchronous aspect of Javascript is similar to coroutines and to continuation passing style (a.k.a. CPS). Look into Continuation Passing C, it is translating a program in CPC (an extended dialect of C, with yield, spawn, wait, ... primitives usable for asynchronous computations) into plain C using continuation passing style techniques.

If your goal is not a general-purpose translator of Javascript to C, but simply to manually rewrite a specific Javascript program into C, coroutines, callbacks, closures, and CPS are still useful concepts to assess. And you could even generate or write code for CPC then use the CPC compiler to get ordinary C.

You might also implement your asynchronous computations using the deprecated setcontext(3) routine, but I don't recommend using that since it is deprecated, very low level (basically it is setting all the machine registers), somehow machine specific, and difficult to debug.

Of course you could also consider multi-threading, e.g. POSIX pthreads or C11 threads.

Licensed under: CC-BY-SA with attribution
scroll top