Synchronizing shared resources with TMonitor
TMonitor is a record used to synchronize threads. Just to be clear, we are talking about System.TMonitor, not Vcl.Forms.TMonitor.
Since Delphi 2009, the TObject instance size has been doubled to make room for an additional 4 bytes. What are these 4 bytes for? They provide TMonitor support!
Now, every TObject descendant can be used as a lock. The type that allows this is the System.TMonitor record, which implements a generic monitor synchronization structure.
Getting ready
In this recipe, you'll face one of the classic multithreading problems—concurrent access to a shared file. Specifically, you'll have a lot of threads writing some information on a file—the same file—and all the threads have to be synchronized for this. Otherwise, the file will not be accessible due to locking, which will cause exceptions in your program code. This problem can be solved in a multitude of ways, but TMonitor offers the simplest solution. Let's start.
How to do it...
Follow...