User:Andrecaldas/MultithreadInTechDraw

From FreeCAD Documentation

Multithreading with TechDraw

xxx

A flow for the processing

In TechDraw, the data might take some time to be generated. So, we protect the data with std::shared_mutex in order to allow it to be read by many at the same time. But we grant exclusive access when the data is modified.

But there are some complications inherent to how TechDraw and FreeCAD organize data. TechDraw processes data that are spread across FreeCAD's document object tree. So...

  1. We cannot simply "lock" everything.
  2. We cannot hold locks during the whole processing, because too many complex processing are done to too much data spread across different DocumentObject instances.

In an ideal world, we would:

  1. Hold a lock while we collect all data we need for the processing.
  2. Then, we would do all the processing using local variables.
  3. And finally, we would simply "atomically swap" the old data and the new data.

This is, however, not quite possible given the way FreeCAD organizes data.

So, what we do is:

  1. We have a set of data that is protected by a shared_mutex.
  2. Any thread can read the data while no thread holds an exclusive lock (is modifying the data).
  3. To modify the data, we do it in chunks. We lock (resume writing) and unlock (stop writing) the mutex many times during the processing.
  4. When we detect that a new thread has started processing the data, we abandon the current processing.

Reading data

Many threads can read the data concurrently, as long as no thread is modifying it.

Nonetheless, it is important to realize that, although the data is supposed to be consistent (in the sense that accessing it shall not lead to a crash), it might happen that it is outdated. Objects referenced or held by us might have been changed, created, removed from the document tree or even been destroyed. Other objects in FreeCAD that could influence our object might have changed, created, removed or destroyed.

It is important to notice that since we do the processing in chunks, the "reading thread" might be reading between two chunks of processing.

Although data that is being processed while the consumed data might have changed, the final data should ultimately be correct. That is because those changes shall trigger a newer update and the old thread will end up being abandoned in favor of a new one.

Writing data

Thread-safe data

Atomic data

Few hypothesis

The GUI