Alternative to Observer Pattern - multithreading

Does anyone know of an alternative to the Observer a.k.a. Listener pattern?
I'm interested in something that would work well in an asynchronous
environment.
The problem I'm facing is that I have an application which uses this
pattern a lot, which is not a bad thing per se, but it becomes a bottleneck as the number of listeners increases. Combined with threading primitives (mutexes, critical sections - of course in my specific environment) the hit on performance is really bad.

How about Message Queue?

If there are too many observers, so the thread being observed is not making any progress, then it might be wise to reverse the relationship. Rather than have the observed thread call out to each and every observer, it may be better to have the observers wait on something like a condition variable or event associated with the observed thread. The observer code can then block, waiting for the condition variable to be signalled. The observed thread can then just signal the condition variable rather than calling into the observers; the observers can notice the signal and process the consequences in their own time.

Please take a look at it if reducing listeners in your code is your primary objective Jeffrey Richter and his AsyncEnumerator. This technique makes asynchronous programmin look more like synchronous.
With this technique your single method could issue an Asynch call and resto fo the method act as an event handler, therefore whole of the invokation and event listener code could be clubbed as one fucntion.

Difficult to say without a more concrete description but the Mediator pattern is related and can be used when the number of communicating objects starts to proliferate. You could implement some policy to co-ordinate the activities a more structured way within these.

Two alternatives from me: using actor model (like akka framework) or using executor to limit the parallelization. Executor is basically just a thread pool which will limit the number of thread and reuse finished threads.

Related

What is the name of this synchronisation method?

I have a special programming construct that allows threads to wait until another thread releases all waiting threads at once.
Each thread can register itself to wait for an external event that can be triggered by another thread (for example one that listens for user input). Once that event occurs all threads can continue and are immediately deregistered.
My question is: What is a construct like this called?
At first I thought of mutex, but as far as i know a mutex is a construct that only allows one thread to run at once (See this link https://www.quora.com/Semaphore-vs-mutex-vs-monitor-What-are-the-differences).
To me this construct sounds like a phaser in java, but my construct does not have a counting logic, so I was wondering what the correct wording is.
Relevant Java and C# classes have the word "barrier" in them, so that might be what you want.
The correct answer is: this is mostly like a condition variable of a monitor. Quoting Wikipedia:
A condition variable essentially is a container of threads that are
waiting for a certain condition. Monitors provide a mechanism for
threads to temporarily give up exclusive access in order to wait for
some condition to be met, before regaining exclusive access and
resuming their task.
An example implementation of this is Java's wait and notifyAll.

multithreading and user interface

Ok, here we go.
recently I got fond of HCI topics on interface design.
I found out that there could be some way to implement a multithread interface in case for reducing the delay of system respons.
Morover. this may also be possible to say that designing a user interface has tight relationship with STD.
therefore, I wonder if there is any method or techniques to find independant part of ,say,a given STD of a UI that can be seen as threads?
A multi threaded interface in most cases is not fundamentally different to it's single threaded counterpart. There is still a single thread listening on interface events and it will still run handlers as events happen. However the difference comes down to what is contained in these handlers. A simple single threaded event loop would look as below:
A multi-threaded UI is a little different but the principal is the same:
Effectively long processes which are initiated in worker threads which can then report back to them main UI thread so it can report completion.
In relation to a State Transition Diagram, multi-threading complicates things somewhat however there a number of ways to still accomplish this. The first is to simply map each (potential) thread's path separately, this requires decisions for if any threads are finished at the points the main thread checks. It is also possible to use a thread state transition diagram which can demonstrate many threads in a single diagram but is sometimes harder to parse.
Now regarding using a state transition diagram to help implement threading in a user interface program you simply have to locate tasks between the event handler and returning to listening which are time consuming and likely to block. You then need to dispatch these tasks as a thread, optionally adding a completion callback in the main thread.
If I have missed anything please comment below, otherwise I hope this is helpful.

How can akka actor interact between threads

I've read akka documentation and can't produce clean understanding of thread interaction while using akka. Docs may omit this thing as obvious but it is not so obvious for me.
All akka actors seemed to be run in same thread they are called. I see actors as co-procedures that just had own stack reset each time receive called.
You may perform a huge chain of actors switching in straight line. Each receive perform small non-blocking operation and force another receive to work further. There is no event loop, that can handle messages outside of the actor system.
I'd like to catch a request from other thread, perform control operations, and wait for another message.
There are some use cases that outline my needs.
There is thread that constantly polling data from some sources. Once data matches pattern it invokes event-driven handler based on actors. Logical controller makes a decision and passes it workers. There should be two persistent thread. One threads works constantly on polling and another works asynchronously to control it work. You should not let akka actors to first thread since they broke polling periods and first thread should not block actors so they need another thread.
There is some kind of two-side board game. One side has a controller thread that schedules calculation time works interacts with board server and etcetera. Other thread is a heavy calculating thread that loops over different variants and could not be written in akka since it has blocking nature
I aware of existing akka futures, but they represent a working task that run once fired and shutting down after performing their goal. The futures are well combined with akka actors, but can not express looped working threads.
Akka actor system incorporates different kinds of network event loops. You may use its built-in remote actor system or well known 0mq protocol. But using network for thread interactions seems like overdoing for me.
What is the supposed way to glue non-akka thread with akka one? Should I wrote a couple of special procedures to perform message passing in thread-safe way?
If you need polling, then the polling thread should just turn whatever is polled into a message and fire it off to an actor.
I find it more useful to use an Actor with a receiveTimeout to do non-blocking polling at an interval, and when there's something that gets polled, it will publish it to some other actor, or perhaps even its ActorSystems' EventStream, for true pub-sub action.

How is ThreadPool implemented in .NET 4.0?

I recently tried to work out how the solution to a ThreadPool class works in .NET 4.0. I tried to read through a reflected code but it seems a bit too extensive for me.
Could someone explain in simple terms how this class works i.e.
How it stores each methods that are coming in
Is it thread safe, supposedly multiple threads try to enqueue their methods in the thread pool?
When it reaches the limit of available threads, how does it return to execute the remaining batch waiting in the queue when one of the threads becomes free? Is there some callback mechanism for it?
Of course, in the absence of the actual implementation (or in the absence of Eric Lippert :) ) what I'm saying is only common sense:
The thread pool holds an internal (circular?) queue where the tasks are kept (hence QueueUserWorkItem).
Putting tasks in the queue is thread-safe (this is for sure, as I've used myself in this scenario several times).
I think that each thread loops indefinitely and keeps taking tasks from the queue (in a thread-safe manner of course) automatically when it's done with the current task. If the queue is empty it will just block.
In a queue of delegates
TBH, I don't know for sure but, if it's not, it's dangerous, nearly useless and probably the worst code ever emitted by M$, (even including Windows ME). Just assume it's thread safe.
The work threads are while loops, waiting on the work request queue for a delegate, invoking one when it becomes available, then looping back round again when the the delegate returns to wait on the queue again for another delegate. There is no need for any callback.
I don't know exectly but to my mind it stores it in a collection of
Task
MSDN says yes
GetMaxThreads() returns the amount of onetime-executed threads if
you reach this border all others are queued. As I understand you
need mechanism for knowing when thread is executed. There is
RegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int32, Boolean)

Multi Threading

How I can determine which thread is waiting for more time?
My requirement is, in a synchronized methods, when one thread finishes its work, I want to allow the thread which is waiting for the longest time. I hope my question make sense.
All depends on which language and/or environment you are using. So far as I know there's no intrinsic support for this in Java, if multiple threads are waiting to enter a synchronized method then the system will pick an arbitrary one to run when entry is possible.
If instead you use Java's wait() / notify() then you control which threads are notified and so can build your own priority mechanism, for example you could have a simple queue to which each thread adds itself before its wait() then you just take the top item from the queue and notify that thread.
You should not and almost certainly do not need to do this.
The threading environment will schedule threads for you.
If the software design is such that this appears to be a problem, then the design is incorrect for a pre-emptive threading environment.
What you may want to be doing is something more like managing and prioritizing units of work, where you for example service work in the order that it arrives.
In other words, the order of work processing should not in your design depend on which thread runs, but rather, on your design of how work is handed out to threads.
#djna Java doesn't let you choose which thread to notify. If 10 threads are in the queue any one of them can be notified.
This can be done by using the lock/condition interfaces in concurrent package.
Here you can associate each of these threads with a condition and then take out an item from that queue and signal the condition that is mapped with that thread/task.

Resources