When we should use NSThreads in a cocoa Touch? - iphone

I am writing a small game by using cocos2d. It is a shooting game. Player on one side and enemy on other side. To run the both actions of player shooting and enemy shooting do we should use threads ? Or can we do without using them. At present I am not using threads. But I can manage to do both actions of player and enemy at same time. Should I use threads compulsory good performance ?
Or am I doing wrong without using threads ? Please help me from this confusion.
Thank you.

You should use threads when it makes sense, i.e., when you would otherwise block the main (UI) thread during a time-consuming operation. Examples of expensive operations include loading images and sounds from disk and retrieving information from a network. For the event loop of a game, threads are not essential because the events in a game are not perfectly simultaneous (indeed, two operations are never simultaneous on the iPhone because it is a single-processor system). Instead, you can perform all of your game logic sequentially and update the UI as necessary. If I'm not mistaken, though, a framework like Cocos2D probably uses a dependency inversion model that calls into your client code, and as such it will create any necessary threads behind the scenes. I'd suggest looking at a tutorial on that specific framework to see what the recommended style is.

Related

What is most useful from C# to code for Unity3D

Does knowing of async and await is useful in Unity?
or knowing asynchronic programming is useful in Unity, or Unity do everything for us?
async and await are useful when doing certain i/o operations, for example when accessing the serial port (which is blocking in Mono otherwise), but this is a realatively narrow area.
Otherwise, normal daily tasks are typically performed on the main thread, as Unity absolutely hates when stuff is called out of order, pretty much crashes immediately.
As for doing multiple things in the background, Unity provides a very conveinient mechanism called Coroutines. Its not actually multithreading but has almost none of the issues real multithreading has.
Asynchronus programming for Unity is probably something you really don't need to learn. I mean, if you want go for it. Always nice to know more about coding.
Unity has certain execution order for all its methods. Just check out the documentation:
https://docs.unity3d.com/Manual/ExecutionOrder.html
As the other answered already states, certain I/O operations, but if you are relatively new to Unity, don't bother about it right now.
Use StartCoroutine(Function()) from the usual functions like Update, Start, Awake or whatever.
Usually you would start IEnumerators in coroutines. Check out Unity docs on that one too:
https://docs.unity3d.com/Manual/Coroutines.html
Cheers.

Unity hard real time synchronization

I need to synchronize Unity app to a 3rd party app where time synchronization is crucial (1-2ms varient max).
The way this is done today (without Unity) is getting priority of the OS scheduler with a designated app which will assure a constant delay.
A constant delay is good enough as it can be used in the data analysis which is not done in real time. Today the constant delay is measured once on the beginning.
Thanks in advance.
This kind of delays should be easy to achieve in a background thread.
Threads work well in Unity, despite common belief. The only thing you need to look out for is not to access Unity objects from the thread.
Easiest way to do this is to start a thread in a MonoBehaviour.Start with the IsBackground property set to true (so you don't have to worry about it blocking your application exit) and communicate to and from it with a message queue (for example a List<Action> with locked access).

Unity Performance - Coroutines vs FSM on update

I just started studying Unity scripting and I'm having a hard time to understand why some people prefer coroutines over state machines.
I do understand that the code might be more readable for some programmers, but I can't understand why some people say that using coroutines are preferable for performance.
I'm using C# in Unity, and from what I understand the C# compiler converts the IEnumerator into a state machine.
So maybe I'm missing something here. Is it better for runtime performance to use Coroutines instead of a FSM loop for handling behavior and states? If yes, why?
Using coroutines is faster in some circumstances because you can conveniently schedule Unity to perform operations at certain intervals rather than doing them every frame, thus saving processing time. It's really the scheduling that saves time, not coroutines as such.
Take the example you highlighted (in you comment in the other answer) from the Unity documentation, where it says:
Use Coroutines. The problem with Update calls is that they happen every frame. Quite possibly checking the distance to the player could be performed only every 5 seconds. This would save a lot of processing power.
This is saying that a coroutine that uses WaitForSeconds( 5f ) will be faster then checking the distance every frame. It doesn't mean that doing so would necessarily be faster than having your own Update logic that only checks distance every five seconds.
Having said that, I wouldn't be surprised if the coroutine approach is still faster (though less dramatically so) than Update-based checking-every-five-seconds logic, because you'd still save on checking the current frame's time every frame in your game code. Yes, somewhere in Unity's engine loop this time check is still happening and being used to determine whether to go to the next coroutine step, but it's likely highly optimized and it's happening anyways, so the coroutine isn't adding as much extra time checking logic as the Update-based approach.
By the way, for a nice outline of how Unity is likely implementing coroutines, see this blog post.
You have to be careful about what you're using coroutines for. They are great for long-running operations that you don't want to hang the game.
However you have to be very careful about how often you yield in the coroutine. Every time you yield, it takes some time (multiple frames) for the coroutine to resume. If you yield too much, your coroutine will be processing slower than it needs to be. For example, I was working on a pathfinding system. I was using a coroutine to periodically yield while it was running the pathfinding algorithm. This was causing the pathfinding code to take much longer than it should have. I found it worked much faster to just do it in Update.
Coroutines are nice for doing long-running asynchronous tasks like a web request, or downloading something in the background, etc. I don't know that I would recommend using coroutines for your main game processing loop. (especially for input)
I don't think that there is a universal answer to that. It very much depends on what you are doing in your code. A badly written Coroutine might be slower than a well-written FSM and vice versa. I'd say readability and understandability of your code always wins over potential (and at this state intanglible) performance gains. If you got a specific performance issue tackle it when you encounter it. So I'd suggest you use the approach that is most intuitive to you and your team.

What to do in a separate thread?

So I've read some stuff about multithreading and NSOperation and wondering how I can use that to improve my app. Using Instruments I have isolated a few places where my app could definitely use a speed improvement. My question is, are these kinds of things suitable for another thread using NSOperation?
Drawing a view: I have a rather complex view that is taking a little time to draw. When it's drawn I experience some lag.
Allocating and playing audio: I'm using AVAudioPlayer to play some background music. When I allocate it, again some lag.
Calculations: I'm also performing some calculations and doing some comparisons with lots of integers.
I strive for the best possible performance for my app, so what would you do?
UI updates are not suitable on the Background thread. All UI updates always need to be done on the main thread. If your view is taking too much time to render, consider refactoring, pre-redering and caching or some other means of optimization.
Audio code can be background based, but shouldn't be that expensive
Calculations can definitely be backgrounded without worry.
I concur that background threads are not the thing to do for UI updates. Since the user is "blocked" on waiting for the UI to show them what is going on - it doesn't make sense from a logical point-of-view - and it can cause other coding issues.
The biggest thing I have found good for background threads often has to do with asynchronous operations. (Think of an AJAX web page). If you want your user to be able to interact with the UI while something is going on. A good example would be retreiving, updating, fetching any kind of data from the web.
Even if you are doing any kind of web operations which you would think should be synchronous - (like loading a message from a web site) - you would probibly want to handle it asynchronously because you don't know what kind of network conditions would cause it to take a long time - and perhaps eventually timeout or fail. (Something like recording audio would work like this too).
Even if you were to want to block your application when reading such a synchronous piece of data from the web, you may still want to do this asynchronously - so you could load the data in a background thread - while you give a progress bar, spinner (progress) control, or allowed the user to hit a "Cancel" button in the foreground UI thread.
Think of "asynchronous" requests as ones that will take a longer period of time - or in which you can't determine how much time it will take.
Some UI drawing methods were made thread safe with iOS 4.0:
source: Apple dev: What's new in iOS: iOS 4.0
Drawing to a graphics context in UIKit is now thread-safe. Specifically:
The routines used to access and manipulate the graphics context can now correctly handle contexts residing on different threads.
String and image drawing is now thread-safe.
Using color and font objects in multiple threads is now safe to do.
I've found that my apps generally benefit the most from background threading:
Downloading things from the web
Expensive queries (reading/writing) to the database
Long running algorithms
If you do decide to background some tasks, I would recommend using NSOperation and NSOperationQueue, as they simplify things a lot. A bit of a learning curve, but definitely worth it!
Best of luck!

Why is a "main" game loop necessary for developing a game?

I find that most game development requires a main game loop, but I don't know why it's necessary. Couldn't we implement an event listener and respond to every user action? Animations (etc.) could then be played when a event occurs.
What is the purpose of a main game loop?
The argument that you "need a loop because otherwise what calls the event listener" does not hold water. Admittedly on any mainstream OS, you do indeed have such a loop, and event listeners do work that way, but it is entirely possible to make an interrupt driven system that works without any loops of any kind.
But you still would not want to structure a game that way.
The thing that makes a loop the most appealing solution is that your loop becomes what in real-time programming is referred to as a 'cyclic executive'. The idea is that you can make the relative execution rates of the various system activities deterministic with respect to one another. The overall rate of the loop may be controlled by a timer, and that timer may ultimately be an interrupt, but with modern OS's, you will likely see evidence of that interrupt as code that waits for a semaphore (or some other synchronization mechanism) as part of your "main loop".
So why do you want deterministic behavior? Consider the relative rates of processing of your user's inputs and the baddies AIs. If you put everything into a purely event based system, there's no guarantee that the AIs won't get more CPU time than your user, or the other way round, unless you have some control over thread priorities, and even then, you're apt to have difficulty keeping timing consistent.
Put everything in a loop, however, and you guarantee that your AIs time-lines are going to proceed in fixed relationship with respect to your user's time. This is accomplished by making a call out from your loop to give the AIs a timeslice in which to decide what to do, a call out to your user input routines, to poll the input devices to find out how your user wants to behave, and call out to do your rendering.
With such a loop, you have to watch that you are not taking more time processing each pass than actually goes by in real time. If you're trying to cycle your loop at 100Hz, all your loop's processing had better finish up in under 10msec, otherwise your system is going to get jerky. In real-time programming, it's called overrunning your time frame. A good system will let you monitor how close you are to overrunning, and you can then mitigate the processing load however you see fit.
An event listener is also dependent on some invocation loop whether you see it or not. Who else is going to call the listener?
Building an explicit game loop gives you absolute control on what's going on so you won't be dependent on whatever some toolkit/event handling library does in its event loop.
A game loop (highly simplified is as follows)
initialise
do
input
update
render
loop
clean up
This will happen every frame the game is drawn. So for games that run at 60fps the above is performed sixty times every second.
This means the game runs smoothly, the game stays in sync and the updates/draws per cycle happen frequently enough. Animation is simply a trick of the eye, objects move between locations but when played quickly enough they appear to be travelling between these locations.
If you were to only update on user input, the game would only react when the user was providing input. Other game components such as A.I game objects would not react on their own. A loop is therefore the easiest and best way of updating a game.
It's not true that all kind of games require a dedicated main game loop.
Action games need such a loop due to frequent object updates and game input precision.
On the other hand, I implemented a minesweeper game and I used window
messages for the notifications.
It's because current operating systems aren't fully event based. Even though things are often represented as events, you'll still have to create a loop where you wait for the next event and process it indefinitely (as an example the Windows event loop). Unix signals are probably the closest thing you get to events on an OS level, but they're not really efficient enough for things like this.
In practical terms, as other people have indicated, a loop is needed.
However, your idea is theoretically sound. You don't need a loop. You need event-based operations.
At a simple level, you can conceptualize the CPU to have a several timers;
one fires on the rising edge of 60Hz and calls the blitting code.
Another might be ticking at 60kHz and be rendering the latest updates of the objects in the game world to the blitter buffer.
Another might be ticking at 10kHz and be taking input from the user. (pretty high resolution, lol)
Another might be the game 'heartbeat' and ticks at 60MHz; AI and physics might operate at heartbeat time.
Of course these timers can be tuned.
Practically, what would be happening is your would be (somewhat elided) like this:
void int_handler1();
//...
int main()
{
//install interrupt handlers
//configure settings
while(1);
}
The nature of games is that they're typically simulations, and are not just reacting based on external events but on internal processes as well. You could represent these internal processes by recurring events instead of polling, but they're practically equivalent:
schedule(updateEvent, 33ms)
function updateEvent:
for monster in game:
monster.update()
render()
vs:
while 1:
for monster in game:
monster.update()
wait(33ms)
render()
Interestingly, pyglet implements the event-based method instead of the more traditional loop. And while this works well a lot of the time, sometimes it causes performance problems or unpredictable behaviour caused by the clock resolution, vsync, etc. The loop is more predictable and easier to understand (unless you come from an exclusively web programming background, perhaps).
Any program that can just sit there indefinitely and respond to user's input needs some kind of loop. Otherwise it will just reach the end of program and will exit.
The main loop calls the event listener. If you are lucky enough to have an event-driven operating system or window manager, the event loop resides there. Otherwise, you write a main loop to mediate the "impedance mismatch" between an system-call interfaces that is based on I/O, poll, or select, and a traditional event-driven application.
P.S. Since you tagged your question with functional-programming, you might want to check out Functional Reactive Programming, which does a great job connecting high-level abstractions to low-level, event-based implementations.
A game needs to run in real-time, so it works best if it is running on one CPU/core continuously. An event-driven application will typically yield the CPU to another thread when there is no event in the queue. There may be a considerable wait before the CPU switches back to your process. In a game, this would mean brief stalls and jittery animation.
Two reasons -
Even event driven systems usually need a loop of some kind that reads events from a queue of some kind and dispatches them to a handler so you end up with an event loop in windows for example anyway and might was well extend it.
For the purposes of animation you'd need to handle some kind of even for every frame of the animation. You could certainly do this with a timer or some kind of idle event, but you'd probably end up creating those in some kind of loop anyway so it's just easier to use the loop
directly.
I've seen systems that do handle it all using events, they have a frame listener that listens to an event dispatched at the start of each frame. They still have a tiny game loop internally but it does little more than handle windowing system events, and create frame events,