问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/4703253/c-cli-thread-synchronization-including-managed-and-unmanaged-code