Kakadu / lablqml

Interfacing Qt/QML with OCaml. Formely known as lablqt
http://kakadu.github.io/lablqml
GNU Lesser General Public License v2.1
159 stars 17 forks source link

Fix description for multi-threading example #20

Open elfring opened 8 years ago

elfring commented 8 years ago

I find the wording "background thread" unusual.

ghost commented 7 years ago

Is this really an issue?

elfring commented 7 years ago

I would appreciate a better description there.

ghost commented 7 years ago

A suggestion would be welcome.

Kakadu commented 7 years ago

First fo all it is weird that github doesn't email updates about the comments.

When we deal with official release of OCaml we can see that it supports (on UNIX) concurrent threads (using pthreads library). By default there is only the main thread which leads the execution of the program, garbage collection and other technical stuff. When we do call another language (let's say C) using FFI in OCaml the execution point moves to the C code and OCaml code and the thread that did that FFI call is kind of paused (which is obvious).

But when we do concurrency in OCaml using pthreads it is possible that an another OCaml thread can move on (when the main thread is stuck in the C code) and trigger garbage collection. I this case some values that are accessed from the C code can be moved which can lead to crash. To deal with it there are two approaches.

With first one you use caml_enter_blocking_section in the beginning of C stub and caml_leave_blocking_section before returning from C stub. It will pause the OCaml runtime, all the threads and GC. This approach is fine when we have main loop in the OCaml code and call C only occasionally.

In lablqt the main loop of the application is the Qt event loop which is started when we do QApplication::exec. So, the approach with locking whole OCaml runtime all the time doesn't fit: we kind of forced to let OCaml runtime gone wild and access OCaml values with all possible precautions. In the demo mentioned above we create a secondary OCaml thread that increments the counter and notifies the main OCaml thread that is actually hanging in the Qt event loop. When this happens Qt commands QML engine to handle this event and continues to loop.