Difference Between Monitor & Lock? - locking

What's the difference between a monitor and a lock?
If a lock is simply an implementation of mutual exclusion, then is a monitor simply a way of making use of the waiting time inbetween method executions?
A good explanation would be really helpful thanks....
regards

For example in C# .NET a lock statement is equivalent to:
Monitor.Enter(object);
try
{
// Your code here...
}
finally
{
Monitor.Exit(object);
}
However, keep in mind that Monitor can also Wait() and Pulse(), which are often useful in complex multithreading situations.
Edit:
In later versions of the .NET framework, this was changed to:
bool lockTaken = false;
try
{
Monitor.Enter(object, ref lockTaken);
// Your code here...
}
finally
{
if (lockTaken)
{
Monitor.Exit(object);
}
}

They're related. For example, in C# the lock statement is a simple try-finally wrapper around entering a Monitor and exiting one when done.

Monitors are compiler-assisted "semi-automatic" locks. They allow one to declare synchronized methods on classes, etc. This is just a different approach to providing mutual exclusion. I found this book to be the most thorough explanation of the concepts, even though it's mostly geared towards OS developers.

A lock ensures mutual exclusion.
A monitor associates the data to be protected and the mutual exclusion and synchronization primitives required to protect accesses to the data.
Synchronization is used e.g. when you need one thread to wait until an event occurs (e.g., wait until another thread places an item in a queue).

Monitors is a programming-language construct that does the same thing as semiphores/locks, but Monitors control the shared data by synchronizing at run time. In contrast, locks protect the shared data by just "spinning" which can lead to poor CPU utilization.

There is no difference, lock generates Monitor.Enter and Monitor.Exit within a try/finally block. Using Monitor over lock allows you to fine tune because it has Pulse and PulseAll. You can also have alternate processing should you be unable to acquire the lock with TryEnter.

Monitor is the concept and Lock is the actual implementation.

As far as I have researched so far, monitor is a set of principles for thread synchronization, while locks are, along with "thread cooperation" facilities like wait and notify, the way monitors are implemented in Java. So effectively, if we try to form the exact relationship between the two notions, locks are one part of the implementation of monitors (the other being wait and notify mechanisms). Please correct me if I'm wrong, but I would really appreciate if the correction is very specific.

Lock focus on only mutual exculsion, but
Moniter provides mutual exclusion automatically.
So we don't need to worry of using mutual exclusion in Monitor.
Instead of ME, we need to consern of sycronzing only when we do programming.
Moniter provides more systematical way of programming.
It, therefor, is more advanced one.

Related

WebFlux locks. How?

I usually write imperative code on Java/Spring MVC, but now my team implement project on WebFlux. I tried to research the topic, but I can't find the answer to the question about locks.
It's normal when we have code that should always be executed by only one thread, or that has locks by some condition (for example, the code should not be executed concurrently for the same entity). These locks can be distributed, for example, through a Redis.
But how is this problem solved in Project Reactor? As far as I understand, it would be a bad idea to use a synchronized block, or ReentrantLock, because they will block threads while we avoid blocking.
It turns out that we need to design the application in such a way that there is no need for locks. Which is not always possible.
Or is there any solution? I will be grateful for any information.
There is no official implementation, here are some resources for reference.
How to trigger Mono execution after another Mono terminates
https://github.com/chenggangpro/reactive-lock

IWantToRunWhenBusStartsAndStops not for production?

New to NServiceBus (4.7.5) and just implemented an NSB host.exe hosted service (implementing IWantToRunWhenBusStartsAndStops) that detects changes to database tables and notifies subscribing web apps by publishing events, e.g. "CustomerDataWasUpdatedEvent". In the future we will perform the actual update through messagehandlers receiving commands obviously, but at the moment this publishing service just polls the database etc.
It all works well, however, approaching production, I noticed that David Boike, in his latest edition of "Learning NServiceBus", states that classes implementing
IWantToRunWhenBusStartsAndStops are really mostly for development and rarely used in production. I set up my database change detection in the Start method and it works nicely, does anyone know why this is discouraged?
Here is the comment in the actual book:
https://books.google.se/books?id=rvpzBgAAQBAJ&pg=PA110&lpg=PA110&dq=nservicebus+iwanttorunwhenbusstartsandstops+in+production+david+boike&source=bl&ots=U6sNII0nm3&sig=qIXffOVFhcy-_3qDnSExRpwRlD4&hl=sv&sa=X&ei=lHWRVc2_BKrWywPB65fIBw&ved=0CBsQ6AEwAA#v=onepage&q=nservicebus%20iwanttorunwhenbusstartsandstops%20in%20production%20david%20boike&f=false
The actual quote is:
...it isn't common to have widespread use of in a production system.
Uncommon is not the same thing as discouraged.
That said I do think there is intent here by the author to highlight the fact that further up the page they assert that this is not a good place to be doing lots of coding, as an unhandled exception can cause the whole process to fail.
The author actually does go on to mention a possible use case for when you may want to load a resource(s) to do work within the handler.
Ok, maybe it's just this scenario we have that is a bit uncommon
Agreed - there is nothing fundamentally wrong with your approach. I recently did the same thing as you for wiring up SqlDependency to listen for database events and then publish a message as a result. In these scenarios there is literally nothing else you can do other than to use IWantToRunAtStatup.
Also, David himself often trawls the nservicebus tag, maybe he'll provide a more definitive answer than mine.
I'll copy the answer I gave in the Particular Software Google Group...
I'll quote myself directly here:
An implementation of IWantToRunWhenBusStartsAndStops is a great place to create a quick interface in order to test messages during debugging by allowing you to send messages based on the console input. Apart from this, it isn't common to have widespread use of them in a production system. One possible production use case will be to provision a resource needed by the endpoint at startup and then tear it down when the endpoint stops.
I think if I could add a little bit of emphasis it would be to "widespread use". I'm not trying to say you won't/can't have an IWantToRunWhenBusStartsAndStops in production code or that avoiding them is a best practice. I am trying to say that having a ton of them is probably a code smell.
Above that paragraph in the book, I warn about IWantToRunWhenBusStartsAndStops not having any ambient transactions or try/catch stuff going on. THAT is really the key part. If you end up throwing an exception in an IWantToRunWhenBusStartsAndStops, tyou can run into big problems. If you use something like a .NET Timer and then throw an exception, you can crash your process!
Let me tell you how I screwed up on this in my first-ever NServiceBus system. The system (still in use today, from what I hear) is responsible for ingesting more than 3000 RSS feeds (probably a lot more than that now) into a CMS. So processing each feed, breaking it up into items, resizing images, encoding attached video for mobile ... all those things were handled in NServiceBus message handlers, which was scaled out to multiple servers, and that was all fantastic.
The problem was the scheduler. I implemented that as an IWantToRunWhenBusStartsAndStops (well, actually IWantToRunAtStartup at that time) and it quickly turned into a mess. I kept the whole table worth of feed information in memory so that I could calculate when to fire off the next ProcessFeed command. I was using the .NET Timer class, and IIRC, I eventually had to use threading primitives like ManualResetEvent in order to coordinate the activity. And because I was using .NET Timer, if the scheduler threw an exception, that endpoint failed and had to restart. Lots of weird edge cases and it was always a quagmire of bugs. Plus, this was now a singleton "commander app" so while the feed/item processors could be scaled out, the scheduler could not.
As I got more experienced with NServiceBus, I realized that each feed should have been a saga, starting from a FeedCreated event, controlled through PauseProcessing and ResumeProcessing commands, using timeouts to control the next processing time, and finally (perhaps) ended via a FeedRemoved event. This would have been MUCH more straightforward and everything would have executed inside transactionally-controlled message handlers.
That experience led me to be a little bit distrustful/skeptical of IWantToRunWhenBusStartsAndStops. Not saying it's bad, just something to be aware of. Always be prepared to consider if what you're trying to do couldn't be better accomplished in another way.

Is it possible to introduce multi threading in dotnet without explicity creating new threads?

I have a loop of several hundred items which need to be processed.
Each item is processed by conditionally setting a global SQLConnection where upon the item is processed using this SQLConnection as part of the processing.
For this reason it is vital that none of these items is allowed to be processed in parallel.
I appreciate that this is not good design and I hope to rectify it as soon as is practical.
However it would seem that despite my best efforts, this code is experiencing some form of multi-threading. Somehow one of these tasks has thrown an exception.
This exception is the violation of a foreign key constraint, but indicates that it was operating against a SQLConnection which it has no business connecting to.
Naturally I have concerns about this, however to my knowledge there is no multi threading code in this app.
I wonder Is it possible to introduce multi threading without explicitly creating new threads
EDIT:
VB.Net 3.5SP1
Console App + Class Libraries
Occasionally Calls out to web services
Makes SQL calls
not much of anything else. No Winforms, no WPF.
Yes - using System.Timers.Timer and/or System.Threading.Timer can cause the effect your describing. Whenever a timer ticks a new work item is queued in the ThreadPool - so essentially you have a multi threading program without explicitly creating new threads.
If the timer is AutoReset (remains enabled after elapsed has been called) you might cause another call to the same handler concurrently.
In addition to the others that have been mentioned: parallel extensions (PLINQ and task parallel library).
Alternatively tasks (ie Task objects) are not called threads, but are. Tasks are commonly found near lambda expressions, check if you have any.
Oh, and async sockets too and all the other async IOs.
BUT:
Instead of trying to avoid multithreading at all cost, wouldn't it be easier to lock ? Sorry if the question is naive, I may miss something.
Could it be that your code is called from a 3rd party library. By using events another library can call your code - from as many threads as it like.
I suggest you check the code that invoke the code that changes and make sure that there's no suspicious calls to your code.

What would a multithreaded UI api look like, and what advantages would it provide?

Or, equivalently, how would you design such an API. Expected/example usage would be illustrative as well.
My curiosity comes directly from the comments (and subsequent editting on my part) of this answer. Similar questions/discussions in the past provide a bit of inspiration to actually asking it.
Executive summary:
I don't feel a multithreaded UI api is possible in a meaningful way, nor particularly desirable. This view seems somewhat contentious and being a (relatively) humble man I'd like to see the error of my ways, if they actually are erroneous.
*Multithreaded is defined pretty loosely in this context, treat** it however makes sense to you.
Since this is pretty free-form, I'll be accepting whichever answer has the most coherent and well supported answer in my opinion; regardless of whether I agree with it.
Answer Accepted
**Ok, perhaps more clarification is necessary.
Pretty much every serious application has more than one thread. At the very least, they'll spin up an additional thread to do some background task in response to a UI event.
I do not consider this a multithreaded UI.
All the UI work is being done on single thread still. I'd say, at a basic level, a multithreaded UI api would have to do away with (in some way) thread based ownership of UI objects or dispatching events to a single thread.
Remeber, this is about the UI api itself; not the applications that makes use of it.
I don't see how a multithreaded UI API would differ much from existing ones. The major differences would be:
(If using a non-GC'd language like C++) Object lifetimes are tracked by reference-counted pointer wrappers such as std::tr1::shared_ptr. This ensures you don't race with a thread trying to delete an object.
All methods are reentrant, thread-safe, and guaranteed not to block on event callbacks (therefore, event callbacks shall not be invoked while holding locks)
A total order on locks would need to be specified; for example, the implementation of a method on a control would only be allowed to invoke methods on child controls, except by scheduling an asynchronous callback to run later or on another thread.
With those two changes, you can apply this to almost any GUI framework you like. There's not really a need for massive changes; however, the additional locking overhead will slow it down, and the restrictions on lock ordering will make designing custom controls somewhat more complex.
Since this usually is a lot more trouble than it's worth, most GUI frameworks strike a middle ground; UI objects can generally only be manipulated from the UI thread (some systems, such as win32, allow there to be multiple UI threads with seperate UI objects), and to communicate between threads there is a threadsafe method to schedule a callback to be invoked on the UI thread.
Most GUI's are multithreaded, at least in the sense that the GUI is running in a separate thread from the rest of the application, and often one more thread for an event handler. This has the obvious benefit of complicated backend work and synchronous IO not bringing the GUI to a screeching halt, and vice versa.
Adding more threads tends to be a proposition of diminishing returns, unless you're handling things like multi-touch or multi-user. However, most multi-touch input seems to be handled threaded at the driver level, so there's usually no need for it at the GUI level. For the most part you only need 1:1 thread to user ratio plus some constant number depending on what exactly you're doing.
For example, pre-caching threads are popular. The thread can burn any extra CPU cycles doing predictive caching, to make things run faster in general. Animation threads... If you have intensive animations, but you want to maintain responsiveness you can put the animation in a lower priority thread than the rest of the UI. Event handler threads are also popular, as mentioned above, but are usually provided transparently to the users of the framework.
So there are definitely uses for threads, but there's no point in spawning large numbers of threads for a GUI. However, if you were writing your own GUI framework you would definitely have to implement it using a threaded model.
There is nothing wrong with, nor particularly special about multithreaded ui apps. All you need is some sort of synchronization between threads and a way to update the ui across thread boundaries (BeginInvoke in C#, SendMessage in a plain Win32 app, etc).
As for uses, pretty much everything you see is multithreaded, from Internet Browsers (they have background threads downloading files while a main thread is taking care of displaying the parts downloaded - again, making use of heavy synchronization) to Office apps (the save function in Microsoft Office comes to mind) to games (good luck finding a single threaded big name game). In fact the C# WinForms UI spawns a new thread for the UI out of the box!
What specifically do you think is not desirable or hard to implement about it?
I don't see any benifit really. Let's say the average app has 3 primary goals:
Rendering
User input / event handlers
Number crunching / Network / Disk / Etc
Dividing these into one thread each(several for #3) would be pretty logical and I would call #1 and #2 UI.
You could say that #1 is already multithreaded and divided on tons of shader-processors on the GPU. I don't know if adding more threads on the CPU would help really. (at least if you are using standard shaders, IIRC some software ray tracers and other CGI renderers use several threads - but i would put such applications under #3)
The user input metods, #2, should only be really really short, and invoke stuff from #3 if more time is needed, that adding more threads here wouldn't be of any use.

Can I implement a cooperative multi-tasking system in VxWorks?

A legacy embedded system is implemented using a cooperative multi-tasking scheduler.
The system essentially works along the following lines:
Task A does work
When Task A is done, it yields the processor.
Task B gets the processor and does work.
Task B yields
...
Task n yields
Task A gets scheduled and does work
One big Circular Queue: A -> B -> C -> ... -> n -> A
We are porting the system to a new platform and want to minimize system redesign.
Is there a way to implement that type of cooperative multi-tasking in vxWorks?
While VxWorks is a priority based OS, it is possible to implement this type of cooperative multi-tasking.
Simply put all the tasks at the same priority.
In your code, where you do your yield, simply insert a 'taskDelay(0);'
Note that you have to make sure the kernel time slicing is disabled (kernelTimeSlice(0)).
All tasks at the same priority are in a Queue. When a task yields, it gets put at the end of the queue. This would implement the type of algorithm described.
I once worked on a relatively large embedded product which did this. Time slicing was disabled and threads would explicitly taskDelay when they wanted to allow another thread to run.
I have to conclude: disabling vxWorks slicing leads to madness. Avoid it, if it is within your power to do so.
Because tasks were entirely non-preemptive (and interrupt handlers were only allowed to enqueue a message for a regular task to consume), the system had dispensed with any sort of locking for any of its data structures. Tasks were expected to only release the scheduler to another task if all data structures were consistent.
Over time the original programmers moved on and were replaced by fresh developers to maintain and extend the product. As it grew more features the system as a whole became less responsive. When faced with a task which took too long the new developers would take the straightforward solution: insert taskDelay in the middle. Sometimes this was fine, and sometimes it wasn't...
Disabling task slicing effectively makes every task in your system into a dependency on every other task. If you have more than three tasks, or you even think you might eventually have more than three tasks, you really need to construct the system to allow for it.
This isn't specific to VxWorks, but the system you have described is a variant of Round Robin Scheduling (I'm assuming you are using priority queues, otherwise it is just Round Robin Scheduling).
The wiki article provides a bit of background and then you could go from there.
Good Luck
What you describe is essentially:
void scheduler()
{
while (1)
{
int st = microseconds();
a();
b();
c();
sleep(microseconds() - st);
}
}
However if you don't already have a scheduler, now is a good time to implement one. In the simplest case, each entry point can be either multiply inherited from a Task class, or implement a Task interface (depending on the language).
you can make all the tasks of same priority and use task delay(0) or you can use tasklock and taskunlock inside your low priority tasks where you need to make non-premptive working.