How to exit playmode from another thread - unity3d

Is it possible (even in a hacky way) to call EditorApplication functions from another thread? More specifically I want to exit play mode from another thread (not main Unity thread).
My use case is, I'm trying to write a small snippet that detects endless loops while in the editor, and breaks out of them in case of detection. So far the "best" I found is killing the process, but this doesn't really help.

You cannot. Unity thread is not like normal programs, in the sense that it is frame-based. You can ask Unity main thread to run methods, by setting a bool that is being checked at every frame or by setting an <Action> Or <Task> Queue, like it is explained in the link suggested by remy_rm in the comment above.
But these hacks don’t run methods on unity main thread, they just gracefully ask Unity main thread itself to run it. The difference, while subtle in normal cases, becomes vital with your problem. You want to call a method on the main thread to kill it when it’s stuck on an endless loop, but isn’t that case, Unity’s main thread will never reach the point in Update() where it’s supposed to kill itself. You basically send a letter to someone who is never coming back home, and he will never read it if he is stuck somewhere and cannot reach home.
Best way, that springs in my mind, in those cases, is to attach a debugger and stop the thread from it.

Related

Directx control in browser plugin

I have to insert a directx control to a firebreath plug in for a browser.
Can anyone post a sample how to do it? I have no knowledge in plugins...
10x
I don't have an example that I can give you, but I can tell you roughly what you need to do.
First, read this: http://colonelpanic.net/2010/11/firebreath-tips-drawing-on-windows/
That will give you an overview of how drawing works in FireBreath.
First, you set everything up when handling AttachedEvent.
Create a new thread to handle drawing (your DirectX drawing must not be on the main thread)
Get the HWND from the PluginWindowWin object (cast the FB::PluginWindow* to FB::PluginWindowWin and call getHWND())
Initialize DirectX on the secondary thread with the provided HWND. Set up some form of render loop and make sure you can send it commands from the main thread.
Handle the RefreshEvent (comes from WM_PAINT) by posting a message somehow to your render thread so it redraws when that event is fired.
Make sure that on DetachedEvent you shut down your thread.
You need to do all initialization, drawing, and shutdown of the DirectX stuff on the same thread. This needs to all happen on a thread that is not just the main thread (don't just use timers) because otherwise it'll mess up the browser rendering context on some versions of Firefox -- not sure why.
Anyway, hope this helps.
Edit: To pass parameters into the start of a boost::thread, should that be the threading abstraction you decide to use, simply pass it in as a parameter.
boost::thread t(&MyClass::someFunction, this, theHWND);
That will start the thread. In actuality, you probably want to make the thread a class variable or something so that you can access it later -- remember that you'll want the thread to have stopped during the handling of DetachedEvent. For messages I'd probably use FB::SafeQueue, which is a threadsafe queue that is part of FireBreath. Look at the sources for how to use it; it's pretty straightforward (stolen from a codeproject article, I think).
// Inside MyClass
void someFunction(HWND theHWND) {
...
}

What is a runloop?

After reading the documentation for NSRunLoop I did not understand very much. I am spawning a secondary thread that has a NSTimer in it that launch every 1sec. Which update a label on the screen with the performSelectorOnMainThread..
However to get it to work I needed a runloop but I do not understand the concept of it?
Anyone who could try to explain it?
Thanks.
A run loop is effectively:
while(... get an event ...)
... handle event ...;
It runs on a thread; the main thread has the main event loop where user events are processed and most UI drawing, etc, occurs. The documentation explains it in detail.
However, in your case, you don't need a thread.
It sounds like all you are doing is periodically updating a label in the UI; something that isn't terribly compute intensive.
Just schedule your timer in the main thread and be done with it. No need for spinning up a thread, using performSelectorOnMainThread:, or incurring all the complexities of guaranteeing data coherency across threads.
Sorry -- didn't understand your question.
Internally, a run loop works by basically putting a flag in the run loop that says "after this amount of time elapses, fire the timer". No additional threads involved and, better yet, it isn't polling to check the time. Think of a run loop as effectively maintaining a timeline. It'll passively let time elapse until there is something of interest found on the timeline (all without polling -- polling sucks. to be avoided.)
It does mean, though, that a Timer will never be 100% accurate. As well, if you have a timer repeating every second, it'll drift over time.
Also; instead of directly triggering a drawing event. Your timer should invalidate the view that needs updating, then let the underlying objects deal with when it is best to actually update the screen.
This page explains it pretty well. FTA:
A run loop is essentially an event-processing loop running on a single thread. You register potential input sources on it, pointing it to the code that it should execute whenever input is available on those sources.

Objective C - Single Background Thread

I want to run a single background thread for an iPhone application which is available in background all the time and gets executed when specific event fires and go to wait for specific event to fire to start its execution again. During the execution of thread if specific event is fired again then thread should restart its work.
I am working on a custom map application. On TouchesMoved event, I need to load the map image tiles according to the positions moved in a background thread. The problem is that when I move the map with speed the touchesMoved event is fired the previous thread has not finished its work and new thread is started. It causes thread safety issue and my application is crashed.
So I am thinking of a solution to have a single thread all the time available and starts its work when touchesMoved is fired if touchesMoved is fired again it should restart its work instead of starting a new thread. I think it will prevent the thread safety issue.
Please help
Firstly I'd echo the use of NSOperation and NSOperationQueue. You could fall-back to using NSThread directly, but the point of NSOperation is that it hides threading from you, leaving you to concentrate on the processing you need to do. Try firing NSOperation requests as and when required, see what the performance is like in your use-case; even if these operations get data in an async manner, it should provide you with a cleaner solution with good performance, plus future proof.
I've successfully used NSInvocationOperation to fire requests as often as required, and it sounds like the sort-of requirements and behaviour you're after. I would suggest more generally that you experiment with these in a test project; here you can test performance.
The following weblog's helped me start playing with NSOperation:
http://www.dribin.org/dave/blog/archives/2009/09/13/snowy_concurrent_operations/
http://www.cimgf.com/2008/02/16/cocoa-tutorial-nsoperation-and-nsoperationqueue/
As always, the Apple Threading Programming Guide is a key read, to figure out which way to go depending on needs.
This sounds like an ideal job for an NSOperationQueue. Have a read of the operation queue section of the concurrency guide.
Essentially, you create an NSOperation object for each map tile load and place them on a queue that only allows them to execute one at a time.
Put a run loop in your background compute thread. Then use an NSOperation queue to manage sending messages to it. The queue plus the run loop will serialize all the work requests for you.

How can i stop the background thread from the main thread in Iphone NSthread?

I start a background thread from my program while my main thread is checking something. If the checking goes false, I want to stop the running background thread and start it all over again with my new parameters.
I want to stop it coz the thread will be downloading images and if I doesnt stop it and call it again, it will take a lot of time for the new images to get downloaded. Is it possible to do so?
In my experience, its usually best to let a thread exit gracefully by itself. How about having some common variable that the main thread could set to false if things go awry. The second thread could periodically check this variable and if it has been set to false, it knows it should clean up and return.
I think you could use condition variables in a more elegant fashion, but his approach with the proper use of NSLock should work.
NSThread implements a method -(void)cancel that sets state information in the receiving thread to indicate, it should exit. The receiving background thread should - if behaving properly - regulary check whether it is cancelled using -(BOOL)isCancelled.
This way the receiver has a chance to clean up it's acquired resources in a proper way.
Looking into the Java language thread semantic, this apparatus works quite the same way. Javas Thread implements two methods void Thread.interrupt() and boolean Thread.isInterrupted().
In case long running background operations do not react to an attempt to -cancel them, i would see this as an serious problem and file a bug report / change request.
You may wait on the termination of the background thread by regulary calling either -(BOOL)isFinished or -(BOOL)isExecuting on the background NSThread. Unfortunately the NSDidBecomeSingleThreadedNotification is not supported on the iPhone plattform.

NSThread Error

I have two uiviewcontrollers. I am using NSThread in first viewcontroller and its works perfect.. Some times the thread was running in the firstviewcontroller, that time i Want to go Secondviewcontroller.This action stops my thread of firstviewcontrollr..
How could i fix this... Can anyone help me?
Thanks in advance
It would be good if you could clarify the question, because it's hard to understand exactly what you want to do and what the problem is. In general, UI code should always run in the main thread. That is clearly stated in the Cocoa documentation, and you will not succeed in having several threads trying to control the UI.
If you want to run code in other threads and have them influence the UI, you need to implement mechanisms to communicate information to the main thread. One method that comes in handy is NSObject's
performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
If you want to use notifications, you must dispatch them on the main thread also. It is easy to get confusing bugs if you don't stick to this principle (although things might seems to work at first).