Rewriting a threaded Objective-C 'story engine' in CoffeeScript: How to script actions & conditions sequentially without a ton of callbacks? - objective-c

I have been experimenting with porting the underlying 'story engine' of my Objective-C iPhone adventure Scarlett and the Spark of Life to HTML5 using CoffeeScript (and I am looking into IcedCoffeeScript).
The graphical part can just use DIVs on the DOM — the requirements there are fairly simple. The problematic part is the 'command and control' story-type commands. The ideal is to be able to express high-level story commands — including conditionals — and have them executed sequentially. So, for example, in faux-CoffeeScript:
scarlett.walkTo(200,300)
scarlett.turnTo(0)
story.wait(0.8)
if interesting
scarlett.think('Looks interesting.')
else
scarlett.think('Looks boring.')
In Objective-C (this was back when scripting languages like Lua were banned on the App Store), we achieved this by having two threads. The main thread ran cocos2d-phone which handled all the OpenGL calls, animation and other cocos niceties. The 'story' thread handled the command-and-control of the story, and if necessary the thread would sleep, awaiting an NSCondition before returning from a function and proceeding to the next call.
It sounds awkward, but it allowed us to express story commands and conditionals in a sequential, natural way, just using normal-looking code. Note that in the example above, the if check for the variable interesting would be evaluated right before Scarlett says something, not at the start of the function. Also, the walkTo(), turnTo(), wait() and think() calls will not return until their associated animation, delay or text box is finished back on the main thread.
What I'm struggling with is how to achieve this expressiveness using web technologies. As I see it, my options are:
Using a Web Worker as the story 'thread'. However, as far as I'm aware, workers can't sleep, and state isn't shared so they can't even perform a busy wait.
Using a callback chain, probably utilising IcedCoffeeScript's await and defer keywords to keep the code tidier. Even with those, though, that's a lot of extra line noise.
Somehow evaluate lines from the story script one-by-one as strings. I can't help feeling that it would be highly problematic.
(Similar in some ways to 3.) Write the story commands in a specially-designed interpreted language, where the program counter could be stopped and started as needed. It seems like this is unnecessarily re-inventing the wheel.
I can't help feeling like I'm overlooking some really obvious solution, though. Am I looking at this back-to-front, somehow? Is there an acknowledged pattern for scripting sequential actions and conditionals over time using actual code, without a mountain of callbacks?

Related

Can I run a DLL in a separate thread?

I have a program I'm writing in vb.net that has ballooned into the most complicated thing I've ever written. Because of some complex math and image rendering that's happening constantly I've been delving into multithreading for the first time to improve overall performance. Things have honestly been running really smoothly, but we've just added more functionality that's causing me some trouble.
The new functionality comes from a pair of DLLs that are each processing a video stream from a USB camera and looking for moving objects. When I start my program I initiate the DLLs and they start viewing the cameras and processing the videos. I then periodically ping them to see if they have detected anything. This is how I start and stop them:
Declare Function StartLeftCameraDetection Lib "DetectorLibLeft.dll" Alias "StartCameraDetection" () As Integer
Declare Function StopLeftCameraDetection Lib "DetectorLibLeft.dll" Alias "StopCameraDetection" () As Integer
When I need to check if they've found any objects I use several functions like this:
Declare Function LeftDetectedObjectLeft Lib "DetectorLibLeft.dll" Alias "DetectedObjectLeft" () As Integer
All of that works really well. The problem is, I've started to notice some significant lag in my UI and I'm thinking it may be coming from the DLLs. Forgive my ignorance on this, but as I said I'm new to using multiple threads (and incorporating DLLs too if I'm honest). It seems to me that when I start a DLL it running it's background tasks on my main thread and just waiting for me to ping it for information. Is that the case? If so, is it possible to have the DLL running on a sperate thread so it doesn't affect my UI?
I've tried a few different things but I can't seem to address the lag. I moved the code that pings the DLL and processes whatever information it gets into a sperate thread, but that hasn't made any difference. I also tried calling StartLeftCameraDetection from a separate thread but that didn't seem to help either. Again, I'm guessing that's because the real culprit is the DLL itself running these constant background tasks on my main thread no what thread I actually call it's functions from.
Thanks in advance for any help you might be able to offer!
There's a lot to grok when it comes to threading, but I'll try to write a concise summary that hits the high points with enough details to cover what you need to know.
Multi-threaded synchronization is hard, so you should try to avoid it as much as possible. That doesn't mean avoiding multi-threading at all, it just means avoiding doing much more than sending a self-contained task off to a thread to run to completion and getting the results back when it's done.
Recognizing that multi-threaded synchronization is hard, it's even worse when it involves UI elements. So in .NET, the design is that any access to UI elements will only occur through one thread, typically referred to as the UI thread. If you are not explicitly writing multi-threaded code, then all of your code runs on the UI thread. And, while your code is running, the UI is blocked.
This also extends to external routines that you run through Declare Function. It's not really accurate to say that they are doing anything with "background tasks on the main thread", if they are doing anything with "background tasks" they are almost certainly implementing their own threading. More likely, they aren't doing any task breakdown at all, and all of their work is being done on whichever thread you use to call them---the UI thread if you're not doing anything else.
If the work being done in these routines is CPU-bound, then it would definitely make sense to push it off onto a worker thread. Based on your comments on what you already tried:
I moved the code that pings the DLL and processes whatever information it gets into a sperate thread, but that hasn't made any difference. I also tried calling StartLeftCameraDetection from a separate thread but that didn't seem to help either.
I think the most likely problem is that you're blocking in the UI thread waiting for a result from the background thread.
The best way to avoid this depends on exactly what the routines are doing and how they produce results. If they do some sort of extended process and return everything in function results, then I would suggest that using Await would work well. This will basically return control to the UI until the operation finishes, then resume whatever the rest of the calling routine was going to do.
Note that if you do this, the user will have full interaction with the UI, and you should react accordingly. You might need to disable some (or all) operations until it's done.
There are a lot of resources on Async and Await. I'd particularly recommend reading Stephen Cleary's blog articles to get a better understanding of how they work and potential pitfalls that you might encounter.

Synchronization and threading for an agent-based modeling project in Objective-C

First of all, I'm an Objective-C novice. Most of my background is in Java.. Also since most Objective-C questions revolve around Cocoa, I should point out that this is on GNUStep.
For a school project, I'm creating a simple agent-based-modeling framework. These frameworks are typically used to model complex systems (like the spreading of diseases). My framework features two main objects: a world and a bug. The world consists of "layers", each of which is associated with a toroidal grid. The world can be populated by bugs, and each bug has an x and a y coordinate, and a layer that it belongs to.
My general idea is to populate the world with bugs, and then fire of threads for each of the bugs and let them do what they want. You can create any kind of bug by subclassing the main Bug class and by implementing an act method defined in a protocol. This way you can have various types of custom bugs and custom behavior. Bugs should be able to interact with the world and each other (removing bugs from the world, adding bugs to the world, moving itself around). As you can see, this is quickly headed to multi-threading hell.
Currently I have a bunch of #synchronized blocks and I'm having a hard time ensuring that the world always remains in a consistent state. This is made especially difficult since the bug needs to communicate with and act on the world and vice-versa. I am trying to implement a simple bug called a RandomBug that randomly moves around the world. Even this is proving to be difficult because I'm seeing potential problems where state can become corrupted or invalid.
I started taking a look at NSOperation and NSOperationQueue because it appears that this might make things easier. I have two questions pertaining to this:
Is there an easy way to perform NSOperations repeatedly (i.e., at specific intervals).
If I set the number of maximum concurrent operations on the thread to 1, do I still need #synchronized blocks? Wouldn't only one thread be interacting with the world at a given time?
Is there a better way to tackle this sort of problem (multiple threads interacting with one shared resources in a repeated manner)?
Should I forgo threading altogether and simply iterate through bugs on the world and activate them in a random manner?
Sounds like you might want something ala a game/simulation loop... So you have an "update world" phase of your run loop for each time step of your simulation (triggered by an NSTimer), where each bug gets a chance to interact with the world; repeat. Unless your bugs are CPU intensive, this might be the way to go....
As for using NSOperation--sure, this will potentially let you use all your CPU cores, however if there's lots of contention for accessing the world state, this may not be a win after all. In that case, you might try making each tile of your world a separate object you can #synchronized against, reducing contention and allowing better use of your CPU(s).
Using a single NSOperationQueue and setting maxConcurrentOperations = 1 is the same as implementing a game loop, basically. If you use an NSOperationQueue, but don't set maxConcurrentOperations, I'd expect NSOperationQueue to run as many operations simultaneously as you have CPU cores.

How should I design notifications in Cocoa if I plan to optimize for concurrency later?

In my app, I want to create a class that receives a certain type of notifications, begins it's work and sends out notifications when it's done. I think that later I may need to use concurrency to optimize the app — so this work that the class does is done in separate threads — but right now I don't have any knowledge or experience of working with concurrency and I don't want to spend time on premature optimizaion. However, if I understand correctly, the default usage of notifications doesn't mix with concurrency so well.
Is there a way that I can just follow few simple rules with notifications right now without diving into concurrency, and avoid rewriting all that code later?
Yes, you can avoid a rewrite.
I would write your work/background tasks inside blocks and use GCD (Grand Central Dispatch). This works fine and is easy to use in the non-parallel case, but will also allow you to easily parallelize your work later.
I'd look into NSBlockOperation and NSOperationQueue and/or dispatch_async()

Compromising design & code quality to integrate with existing modules

Greetings!
I inherited a C#.NET application I have been extending and improving for a while now. Overall it was obviously a rush-job (or whoever wrote it was seemingly less competent than myself). The app pulls some data from an embedded device & displays and manipulates it. At the core is a communications thread in the main application form which executes a 600+ lines of code method which calls functions all over the place, implementing a state machine - lots of if-state-then-do type code. Interaction with the device is done by setting the state/mode globally and letting the thread do it's thing. (This is just one example of the badness of the code - overall it is not very OO-like, it reminds of the style of embedded C code the device firmware is written in).
My problem is that this piece of code is central to the application. The software, communications protocol or device firmware are not documented at all. Obviously to carry on with my work I have to interact with this code.
What I would like some guidance on, is whether it is worth scrapping this code & trying to piece together something more reasonable from the information I can reverse engineer? I can't decide! The reason I don't want to refactor is because the code already works, and changing it will surely be a long, laborious and unpleasant task. On the flip side, not refactoring means I have to sometimes compromise the design of other modules so that I may call my code from this state machine!
I've heard of "If it ain't broke don't fix it!", so I am wondering if it should apply when "it" is influencing the design of future code! Any advice would be appreciated!
Thanks!
Also, the longer you wait, the worse the codebase will smell. My suggestion would be first create a testsuite that you can evaluate your refactoring against. This makes it a lot easier to see if you are refactoring or just plain breaking things :).
I would definitely recommend you to refactor the code if you feel its junky. Yes, during the process of refactoring you may have some inconsistencies/problems at the start. But that is why we have iterations and testing. Since you are going to build up on this core engine in future, why not make the basement as stable as possible.
However, be very sure on what you are going to do. Because at times long lines of code does not necessarily mean evil. On the other hand they may be very efficient in running time. If/else blocks are not bad if you ask me, as they are very intelligent in branching from a microprocessor's perspective. So, you will have to be judgmental and very clear before you touch this.
But once you refactor the code, you will definitely have fine control over it. And don't forget to document it!! Tomorrow, someone might very well come and say about you on whatever you've told about this guy who have written that core code.
This depends on the constraints you are facing, it's a decision to be based on practical basis, not on theoretical ones. You need three things to consider.
Time: you need to have enough time to learn it, implement it, and test it, without too many other tasks interrupting you
Boss #1: if you are working for someone, he needs to know and approve the time and effort you will spend immediately, required to rebuild your solution
Boss #2: your boss also needs to know that the advantage of having new and clean software will come at the price of possible regressions, and therefore at the beginning of the deployment there may be unexpected bugs
If you have those three, then go ahead and refactor it. It will be surely be worth it!
First and foremost, get all the business logic out of the Form. Second, locate all the parts where the code interacts with the global state (e.g. accessing the embedded system). Delegate all this access to methods. Then, move these methods into a new class and create an instance in the class's constructor. Finally, inject an instance for the class to use.
Following these steps, you can move your embedded system logic ("existing module") to a wrapper class you write, so the interface can be nice and clean and more manageable. Then you can better tackle refactoring the monster method because there is less global state to worry about (only local state).
If the code works and you can integrate your part with minimal changes to it then let the code as it is and do your integration.
If the code is simply a big barrier in your way to add new functionality then it is best for you to refactor it.
Talk with other people that are responsible for the project, explain the situation, give an estimation explaining the benefits gained after refactoring the code and I'm sure (I hope) that the best choice will be made. It is best to speak about what you think, don't keep anything inside, especially if this affects your productivity, motivation etc.
NOTE: Usually rewriting code is out of the question but depending on situation and amount of code needed to be rewritten the decision may vary.
You say that this is having an impact on the future design of the system. In this case I would say it is broken and does need fixing.
But you do have to take into account the business requirements. Often reality gets in the way!
Would it be possible to wrap this code up in another class whose interface better suits how you want to take the system forward? (See adapter pattern)
This would allow you to move forward with your requirements without the poor design having an impact.
It gives you an interface that you understand which you could write some unit tests for. These tests can be based on what your design requires from this code. It ensures that your assumptions about what it is doing is correct. If you say that this code works, then any failing tests may be that your assumptions are incorrect.
Once you have these tests you can safely refactor - one step at a time, and when you have some spare time or when it is needed - as per business requirements.
Quite often I find the best way to truly understand a piece of code is to refactor it.
EDIT
On reflection, as this is one big method with multiple calls to the outside world, you are going to need some kind of inverse Adapter class to wrap this method. If you can inject dependencies into the method (see Dependency Inversion such that the method calls methods in your classes then you can route these to the original calls.

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.