I am working on a wrapper class for an unmanaged algorithm class. I've come to a point where I need separate threads for the processing and on-the-fly display of the results.
I have a single method in my unmanaged class that does the work(I don't think I can change that). Inside it there is a main loop. My plan was to enable drawing the results at the end of each iteration.
I wanted to use System::Threading::Monitor methods to perform the synchronization. However they require a managed reference to work which I cannot create in an unmanaged class. How am I supposed to solve that problem and perform thread synchronization?
Either switch your class to managed, or use unmanaged synchronization objects. If you for some reason cannot change the algorithm to be managed, you can have two classes - one managed, the other one unmanaged with algorithm. The first one will use functionality of the other one and will provide synchronization using Monitor for it.
Or, if you want to keep whole code unmanaged, go to Windows API for synchronization. See MSDN list of functions - look at CreateMutex, CreateSemaphore and InitializeCriticalSection for more information. Mutex and critical section are very similar to simple lock provided by Monitor class. (In fact, Monitor is implemented to work the same way as them, adding some more functionality for signalling.) See CreateEvent for information on signalling.
Related
I read that mutex is a semaphore with value 1 (binary semaphore) used to enforce mutual exclusion.
I read this link
Semaphore vs. Monitors - what's the difference?
which says that monitor helps in achieving mutual exclusion.
Can someone tell me the difference between mutex and monitor as both help achieve the same thing (Mutual Exclusion)?
Since you haven't specified which OS or language/library you are talking about, let me answer in a generic way.
Conceptually they are the same. But usually they are implemented slightly differently
Monitor
Usually, the implementation of monitors is faster/light-weight, since it is designed for multi-threaded synchronization within the same process. Also, usually, it is provided by a framework/library itself (as opposed to requesting the OS).
Mutex
Usually, mutexes are provided by the OS kernel and libraries/frameworks simply provide an interface to invoke it. This makes them heavy-weight/slower, but they work across threads on different processes. OS might also provide features to access the mutex by name for easy sharing between instances of separate executables (as opposed to using a handle that can be used by fork only).
Monitor are different then Mutex but they can be considered similar in a sense that Monitor are build on top of Mutex. See depiction of monitor in an image at the bottom, for clarity.
Monitor is a synchronization construct that allows threads to have both mutual exclusion (using locks) and cooperation i.e. the ability to make threads wait for certain condition to be true (using wait-set).
In other words, along with data that implements a lock, every Java object is logically associated with data that implements a wait-set. Whereas locks help threads to work independently on shared data without interfering with one another, wait-sets help threads to cooperate with one another to work together towards a common goal e.g. all waiting threads will be moved to this wait-set and all will be notified once lock is released. This wait-set helps in building monitors with additional help of lock (mutex).
I you want, you can see my answer here, which may or may not be relevant to this question.
You can find another relevant discussion here
Semaphore vs. Monitors - what's the difference?
Unfortunately the textbook definitions does not always correspond to how different platforms and languages use the terms. So to get precise answers you have to specify the platform and context. But in general:
A mutex is a lock which can only be owned by a single thread at a time. The lock doesn't in itself protect anything, but code can check for ownership of a mutex to ensure that some section of code is only executed by a single thread at a time. If a thread wants to acquire a mutex lock the thread is blocked until it becomes available.
In Java terminology a monitor is a mutex lock which is implicitly associated with an object. When the synchronized keyword is applied to classes or methods an implicit mutex lock is created around the code, which ensures that only one thread at a time can execute it. This is called a monitor lock or just a monitor.
So in Java a monitor is not a specific object, rather any object has a monitor lock available which is invoked with the synchronized keyword.
The synchronized keyword can also be used on a block of code, in which case the object to lock on is explicit specified. Here it gets a bit weird because you can use the monitor of one object to lock access to another object.
In computer science textbooks you may meet a different kind of monitor, the Brinch-Hansen or Hoare-monitor, which is a class or module which is implicitly thread-safe (like a synchronized class in Java) and which have multiple conditions threads can wait/signal on. This is a higher-level concept than the Java monitor.
C#/.NET has monitors similar to Java, but also have a Mutex class in the standard library - which is different from the mutex lock used in the monitor. The monitor lock only exist inside a single process, while the Mutex-lock is machine wide. So a monitor lock is appropriate for making objects and data-structures thread safe, but not for providing system-wide exclusive access to say a file or device.
So bottom line: These terms can mean different things, so if you want a more specific answer you should specify a specific platform.
I know that you need synchronize (yourprocedure) to set e.g. a label's text.
But what about:
Reading a label's text.
Toggle/Set the label's enabled property.
Call other labels procedures/functions (e.g. onclick event).
Is there an easy rule to know/remember when I need to use synchronize?
PS.: Is synchronize similar to PostMessage/SendMessage?
Easy rule of thumb: ANY access to VCL UI components needs to be synchronized. That includes both reading and writing of UI control properties. Win32 UIs, most notably dialogs like MessageBox() and TaskDialog(), can be used directly in worker threads without synchronizing.
TThread.Synchronize() is similar to SendMessage() (in fact, it used to be implemented using SendMessage() internally in Delphi 5 and earlier). TThread.Queue() is similar to PostMessage().
Any time you access a VCL UI component, you need to implement some type of thread safety measure. This is also, typically, the case when you're accessing a variable or procedure that exists or will be accessed by another thread. However, you don't need to use the Synchronize method in all of these situations. There are other tools at your disposal, and Synchronize is not always your best solution.
Synchronize blocks both the main thread and the calling thread while it's performing the procedure that you pass to it, so overusing it can detract from the benefits of multi-threading. Synchronize is probably most commonly used for updating your UI, but if you find that you're having to use it really frequently, then it might not be a bad idea to check and see if you can restructure your code. I.E. do you really need to read labels from within your thread? Can you read the label before starting the thread and pass it into the thread's constructor? Can you handle any of these tasks in the thread's OnTerminate event handler?
I'm trying to write a library to separate all the disk activity out into its own thread, but the documentation doesn't really care about such things.
What I want to accomplish is that aside from startup, all disk activity is asynchronous, and for that, I need to wrap every class that accesses the disk. Here's what I found so far:
QtCore:
QFile
QTemporaryFile
QDir
QFileInfo
QFileSystemWatcher
QDirIterator
QSettings
QtGui:
QFileDialog
QFileSystemModel
QDirModel
I'm sure there are more.
I have a couple of points -
First, when you do this, remember that all GUI objects are based on QWidget, have run in the start-up thread. See http://doc.trolltech.com/4.6/threads-qobject.html which talks about threading. The quote is "Although QObject is reentrant, the GUI classes, notably QWidget and all its subclasses, are not reentrant. They can only be used from the main thread. As noted earlier, QCoreApplication::exec() must also be called from that thread".
This also means that if you need to display information from one of these wrapper classes on the screen, you need to be careful about ownership of objects when you pass information back to the GUI thread. Particularly, anything that is based on QObject.
Second, starting threads carries a run-time cost. So I would suggest that you structure your design to minimize the number of times this wrapper thread class is created and destroyed.
Overall an interesting approach to files. This is one that I'm going to consider for my current application. It may solve some problems I'm having.
I have a native Visual C++ COM object and I need to make it completely thread-safe to be able to legally mark it as "free-threaded" in th system registry. Specifically I need to make sure that no more than one thread ever accesses any member variable of the object simultaneously.
The catch is I'm almost sure that no sane consumer of my COM object will ever try to simultaneously use the object from more than one thread. So I want the solution as simple as possible as long as it meets the requirement above.
Here's what I came up with. I add a mutex or critical section as a member variable of the object. Every COM-exposed method will acquire the mutex/section at the beginning and release before returning control.
I understand that this solution doesn't provide fine-grained access and this might slow execution down, but since I suppose simultaneous access will not really occur I don't care of this.
Will this solution suffice? Is there a simpler solution?
This solution should work, but I'd recommend mutexes over critical sections as they handle time-outs, which provide some level of fall back in case of deadlock. You also want to be very careful that a function locking a mutex does not call another function that has already locked the same mutex in the same thread. This shouldn't be a problem for your COM interface, so long as you don't add extra functionality on top of your mutex to the interface. You could hit issues if the COM includes call backs.
If you are certain that actual concurrent access is not going to happen in practice, then mutexing the entire execution is not an unreasonable approach.
Can you suggest an approach when design-time components can be accessed both from general code (VCL or other) and from my own threads?
The problem is that when I have full control over my own threads I know exactly when I should access mutexes. In case of design-time elements I have no control at least of the code related to VCL.
One of the variants would be to wrap HandleMessage in a mutex access code. The idea behind this is that almost everything related to VCL comes from message processing code (the exception is direct SendMessage handling). But looking at the sources I see no "official" way to wrap message handling in any code fragment.
Don't even try to go there. Google for "global interpreter lock" (Python specific) to see what a bad idea such a bottleneck is.
If you need synchronized access to data, try to make the locked access as short as possible, and lock not any higher in the call chain than you absolutely must. If you have objects that are to be accessed from multiple threads, then synchronize inside their methods.