Pin/Run Akka Actor to Main Thread - multithreading

I'm currently poking at using Scala and Akka in an application that uses LWJGL. As is commonly known, you can't really issue OpenGL calls outside of the main thread of the application. This poses a problem if I want to use any actor for rendering (either a single, main actor that, for example, drains a rendering command queue, or having multiple actors that might issue arbitrary OpenGL commands at any time) as I have not seen a way to run any actor on a specific thread. Either by pinning a specific actor to a thread, or by instructing an actor to run on a specific thread at some point. (a la Objective-C's performSelectorOnMainThread)
Is there a way to pin a "rendering" actor to the main thread, or have any actor run on the main thread at some point in the future, at which point it will be able to issue OpenGL calls? (or even some other solution, I'm open to ideas)

To pin execution thread of Akka actor you can use custom executor service configuration:
akka {
...
actor {
...
my-dispatcher {
executor = "com.github.plokhotnyuk.actors.CustomExecutorServiceConfigurator"
}
}
}
class CustomExecutorServiceConfigurator(config: Config, prerequisites: DispatcherPrerequisites) extends ExecutorServiceConfigurator(config, prerequisites) {
def createExecutorServiceFactory(id: String, threadFactory: ThreadFactory): ExecutorServiceFactory = new ExecutorServiceFactory {
def createExecutorService: ExecutorService = myExecutorService()
}
}
Full example is here

Related

Updating UI from background thread SWIFT

I'm using this code for background work:
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, {
// Some work in the background and updating UI too.
});
However I was reading here that we should use:
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
// do some task
dispatch_async(dispatch_get_main_queue()) {
// update some UI
}
}
when updating UI.
My question is: In the code sample I am using the UI gets updated in the global queue and UI is updated without errors. What is the difference between the approach I am using, and the approach mentioned in the link above?
P.S: the code is executed on Mac OS X 10.10
Thread Safety Summary in the
"Threading Programming Guide" states:
Main Thread Only Classes
The following classes must be used only from the main thread of an
application.
NSCell and all of its descendants
NSView and all of its descendants.
For more information, see NSView Restrictions.
The only dispatch queue that is bound to the main thread is
the main queue that you get with dispatch_get_main_queue().
dispatch_get_global_queue() returns a global concurrent queue
which is not the main queue, and therefore may execute its work
on secondary threads. Therefore updating the UI from this queue
may work by chance, but it can also cause delayed UI updated,
non-working UI updates or crashes.

Scala actors, futures and system calls resulting in Thread leaks

I am running a complex software with different actors (scala actors). Some of them have some executions that uses scala futures to avoid locking and keep processing new received messages (simplified code):
def act {
while (true) {
receive {
case (code: String) =>
val codeMatch = future { match_code(code) }
for (c <- codeMatch)
yield callback(code)(JSON.parseJSON(c))
}
}
}
def match_code(code: String) {
val result = s"my_script.sh $code" !!
}
I noticed looking at jvisualvm and Eclipse Debugger that the number of active threads keeps increasing when this system is running. I am afraid I am having some kind of Thread leak, but I can't detect where is the problem.
Here are some screenshots of both finished and live threads (I hided some live threads that are not related to this problem)
Finished Threads
Living threads
Edit 1:
In the above graphs example, I run the system with only 3 actors of different classes: Actor1 sends messages to Actor2 that sends message to Actor3
You are using receive so each actor will use its own thread, and you don't at least in this example provide any way for actors to terminate. So you would expect to have one new thread per actor that was ever started. If that is what you see, then all is working as expected. If you want to have actors cease running, you will have to let them eventually fall out of the while loop or call sys.exit on them or somesuch.
(Also, old-style Scala actors are deprecated in favor of Akka actors in 2.11.)
You also don't (in the code above) have any indication whether the future actually completed. If the futures don't finish, they'll keep tying up threads.

How to set up a Scala actor to exclusively use a separate thread to run?

As far as I understand, Scala manages a thread pool to run actors, sharing threads among them. Can I set up a particular actor to run in a separate thread exclusively, never sharing it with another actor?
It sounds like you are using Scala (not Akka) actors. In that case if you use the receive or receiveWithin style of message handling then each actor will get its own thread. Using the react style of message handling shares a thread pool among actors.
When I say the receive "style", I mean in a loop, for example:
val timerActor = actor {
while (true) {
receiveWithin(60 * 1000) {
case Stop => self.exit()
case TIMEOUT =>
destination ! Tick
}
}
}
In this case timerActor does not share its thread with any other actor. receiveWithin will block until either the actor receives a Stop message or 60 seconds passes. If 60 seconds passes then the TIMEOUT case is executed.
If you want to learn the gritty details about Scala actors, check out the paper Actors That Unify Threads and Events.
Akka also supports thread-based actors in addition to event-based actors.

In Silverlight UI thread, when doing InvokeAsync what happens?

I am trying to solve SL performance issues.
Up until now I had WCF calls which were executed by InvokeAsync.
Now, I changed it to use the BackgroundWorker.
Performance is greatly improved.
what can cause this? what does InvokeAsync did exactly that affected the UI thread? is it opening another UI thread?
Thanks
It comes down to Synchronization contexts. A thread may be associated with SynchronizationContext such as the DispatcherSynchronizationContext (which is the context of the UI thread and only contains this one thread). WCF will complete an operation in the same Synchronization context that it began in, if there is no synchronization context associated with the thread it will use any thread in the thread pool.
Hence if you have several outstanding async operations all invoked from the UI Thread then all those operations will want to run their completion code in the UI Thread. If a number of them complete at the same time the completion code will have to queue up waiting to be dispatched into this single UI thread.
Whereas when you invoke async operations in a Background worker its running in a thread from the thread pool and does not have special synchronisation context. When those operations complete their completion code may run on any available thread in the pool (of which there are several). So near simultaneous completions can all run in parallel on different threads.
In WPF and Silverlight i recommend to use SynchronazationContext to save the main thread, all other thread will use this instance of SynchronazationContext to access the main thread (UI). You use it in this manner (Note: i generated a method that do this and all other methods will access this method to update the UI):
SynchronazationContext ctx = null;
void DoSomething()
{
ctx = SynchronazationContext.Current;
//Some algorithm here
this.UpdatePic("Success !");
}
void ThreadProc()
{
SendOrPostCallback callBack = new SendOrPostCallback(UpdatePic);
ctx.Post(callBack, String.Format("Put here the pic path");
}
void UpdatePic(string _text)
{
//This method run under the main method
}
In .NET 5.0 you can call this complicated functions by mark the method as async and write 'await' when you call the synchronous method - that make the synchronous method as asynchronous method and update the UI with the main thread.

Threading 101: What is a Dispatcher?

Once upon a time, I remembered this stuff by heart. Over time, my understanding has diluted and I mean to refresh it.
As I recall, any so called single threaded application has two threads:
a) the primary thread that has a pointer to the main or DllMain entry points; and
b) For applications that have some UI, a UI thread, a.k.a the secondary thread, on which the WndProc runs, i.e. the thread that executes the WndProc that recieves messages that Windows posts to it. In short, the thread that executes the Windows message loop.
For UI apps, the primary thread is in a blocking state waiting for messages from Windows. When it recieves them, it queues them up and dispatches them to the message loop (WndProc) and the UI thread gets kick started.
As per my understanding, the primary thread, which is in a blocking state, is this:
C++
while(getmessage(/* args &msg, etc. */))
{
translatemessage(&msg, 0, 0);
dispatchmessage(&msg, 0, 0);
}
C# or VB.NET WinForms apps:
Application.Run( new System.Windows.Forms() );
Is this what they call the Dispatcher?
My questions are:
a) Is my above understanding correct?
b) What in the name of hell is the Dispatcher?
c) Point me to a resource where I can get a better understanding of threads from a Windows/Win32 perspective and then tie it up with high level languages like C#. Petzold is sparing in his discussion on the subject in his epic work.
Although I believe I have it somewhat right, a confirmation will be relieving.
It depends on what you consider the primary thread. Most UI frameworks will have an event handler thread that sits mostly idle, waiting for low level events. When an event occurs this thread gets a lock on the event queue, and adds the events there. This is hardly what I'd consider the primary thread, though.
In general a dispatcher takes some events and, based on their content or type sends (dispatches, if you will) them to another chunk of code (often in another thread, but not always). In this sense the event handler thread itself is a simple dispatcher. On the other end of the queue, the framework typically provides another dispatcher that will take events off of the queue. For instance, sending mouse events to mouse listeners, keyboard events to keyboard listeners etc.
Edit:
A simple dispatcher may look like this:
class Event{
public:
EventType type; //Probably an enum
String data; //Event data
};
class Dispatcher{
public:
...
dispatch(Event event)
{
switch(event.type)
{
case FooEvent:
foo(event.data);
break;
...
}
};
Most people I've met use "dispatcher" to describe something that's more than just a simple passthrough. In this case, it performs different actions based on a type variable which is consistent with most of the dispatchers I've seen. Often the switch is replaced with polymorphism, but switch makes it clearer what's going on for an example.

Resources