how to use c# threads in unity3d for android platform? - multithreading

I am in need to load files, scenes and play animations in threads..
Tried loading files via www in Android...
how to do other stuff via threads?
But how come a game engine doesn't allow us to create threads?
or my understanding is wrong?
how can one create threads in UNITY3D?

You can use threads in Unity but the engine is not thread safe. Usually you run detached threads (from the Unity UI) to do long running processes and check on results (you cannot interact with Unity from the working thread).
The common approach is to use a class which represents a threading job which will be initialized by the Unity main thread. Then you start a worker thread on a function of that class and let it do it's job (Coroutines run on the Unity main thread so are not real threads. Best article on Coroutines is here)
Here's an example of the approach described above (see accepted answer):
http://answers.unity3d.com/questions/357033/unity3d-and-c-coroutines-vs-threading.html
You might also want to try a UnityGems package that achieves the same effect but provides convenience (such as closure support). See this page
HTH.
Best!

From my own personal experience with Unity, you cannot create/run a separate thread unless the thread doesn't use any of Unity's api. So that means no gameObjects or things of similar nature.I've successfully done it myself for my own pathfinding so I know it is possible. Good Luck! I hope this helps.

A commonly used approarch in Unity3D is to use Coroutines.
IEnumerator DoSth()
{
...
yield retrun ... ;
}
To call/Consume the coroutine:
StartCoroutine(DoSth()); // OK
StartCoroutine("DoSth"); // Also fine
StopCoroutine("DoSth"); // You can stop it as well

Related

firefox addon: create a new thread and dispatch nsIRunnable to it?

Why does this crash FireFox? Copy and paste this code into the browser console (Ctrl+Shift+J):
function TestRunner(){}
TestRunner.prototype={
classDescription:"TestRunner",
classID:Components.ID("{09AA3487-7531-438D-B0B2-80BC24B584C0}"),
contractID:"#yoy.be/TestRunner;1",
QueryInterface:XPCOMUtils.generateQI([Components.interfaces.nsIRunnable]),
run:function(){
console.log("ping");
}
};
Components.classes["#mozilla.org/thread-manager;1"].getService().newThread(0).dispatch(new TestRunner(),0);
Starting with Firefox 4(-ish) the whole Javascript engine became far less thread safe, to the extend where e.g. simple things such as just "reading" a string concurrently may cause memory corruption (because these reads might actually materialize strings views for string ropes).
Therefore it was decided that dispatching javascript-implemented nsIRunnable isn't supported anymore as there is no safe way to use it, and people should switch over to ChromeWorkers where possible.
Edit You said in the comments that you wanted to implement nsIChannel/nsIProtocolHandler. AFAIK you can implement nsIProtocolHandler and nsIChannel without any threads and binaries. If you still have to have threads and/or binaries, then your Javascript XPCOM (stub) components would "simply" communicate with a ChromeWorker via message passing (pass around ArrayBuffers/typed arrays; those are zero-copy). The ChromeWorker would then do any heavy lifting, incl. any js-ctypes calls to interface with binaries.
You can run non-XPCOM JavaScript on other threads using (chrome) workers, and you can dispatch C++ implementations of nsIRunnable to other threads, but you can only use XPConnect on the main thread. This is because XPConnect objects could be cycle-collected and the cycle collector isn't threadsafe.

multithreading and responsiveness of adobe air desktop

how can i achieve multithreading in adobe air desktop for Linux?
my UI is sometimes unresponsive because of heavy computations (client/server sockets, sql updates and inserts).
I want to have a thread processing these computation in the background and in Real-Time (UI should not be interrupted with modals/dialogs saying "loading")
can a native process helps this kind of situation? i was googling for hours and i found this so-called "green threads" but it doesn't help me...
does native process actually creates a new thread?
NOTE : this is for linux
sorry for my english..
In your case I would give a try to Workers http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/Worker.html
I would recommend that you use your main app for UI display and move all "heavy" work (webservice calls, parsers, utility classes) you have implemented so far in en external worker.
A nice tutorial you can find here http://gotoandlearn.com/play.php?id=162
Good luck
just look here https://code.google.com/p/async-threading/.
AsyncThreading is an actionscript library to facilitate threading in Flex and Air applications.It is very simple, just extends AbstractAsyncThread class and implements IAsyncThreadResponder interface, or implement a class extending the IAsyncThreadResponder interface, you can do what you need.
But be carefull when you send a message to another thread, I suggest you get instance of your class but not to receive a message from it.

Does WinRT still have the same old UI threading restrictions?

In WinForms, pretty much all your UI is thread-specific. You have to use [STAThread] so that the common dialogs will work, and you can't (safely) access a UI element from any thread other than the one that created it. From what I've heard, that's because that's just how Windows works -- window handles are thread-specific.
In WPF, these same restrictions were kept, because ultimately it's still building on top of the same Windows API, still window handles (though mostly just for top-level windows), etc. In fact, WPF even made things more restrictive, because you can't even access things like bitmaps across threads.
Now along comes WinRT, a whole new way of accessing Windows -- a fresh, clean slate. Are we still stuck with the same old threading restrictions (specifically: only being able to manipulate a UI control from the thread that created it), or have they opened this up?
I would expect it to be the same model - but much easier to use, at least from C# and VB, with the new async handling which lets you write a synchronous-looking method which just uses "await" when it needs to wait for a long-running task to complete before proceeding.
Given the emphasis on making asynchronous code easier to write, it would be surprising for MS to forsake the efficiency of requiring single-threaded access to the UI at the same time.
The threading model is identical. There is still a notion of single threaded and multi-threaded apartments (STA/MTA), it must be initialized by a call to RoInitialize. Which behaves very much like CoInitialize in name, argument and error returns. The user interface thread is single threaded, confirmed at 36:00 in this video.
The HTML/CSS UI model is inherently single threaded (until the advent of web workers recently, JS didn't support threads). Xaml is also single threaded (because it's really hard for developers to write code to a multithreaded GUI).
The underlying threading model does have some key differences. When your application starts, an ASTA (Application STA) is created to run your UI code as I showed in the talk. This ASTA does not allow reentrancy - you will not receive unrelated calls while making an outgoing call. This is a significant difference from STAs.
You are allowed to create async workitems - see the Windows.System.Threadpool namespace. These workitem threads are automatically initialized to MTA. As Larry mentioned, webworkers are the JS equivalent concept.
Your UI components are thread affined. See the Windows.UI.Core.CoreDispatcher class for information on how to execute code on the UI thread. You can check out the threading sample for some example code to update the UI from an async operation.
Things are different in pretty important ways.
While it's true the underlying threading model is the same, your question is generally related to how logical concurrency works with UI, and with respect to this what developers see in Windows 8 will be new.
As you mention most dialogs previously blocked. For Metro apps many UI components do not block all. Remember the talk of WinRT being asynchronous? It applies to UI components also.
For example this .NET 4 code will not necessarily kill your harddrive because the UI call blocks on Show (C# example):
bool formatHardDrive = true;
if (MessageBox.Show("Format your harddrive?") == NO)
formatHardDrive = false;
if (formatHardDrive == true)
Format();
With Windows 8 Metro many UI components like Windows.UI.Popups.MessageDialog, are by default Asynchronous so the Show call would immediately (logically) fall through to the next line of code before the user input is retrieved.
Of course there is an elegant solution to this based on the await/promise design patterns (Javascript example):
var md = Windows.UI.Popups.MessageDialog("Hello World!");
md.showAsync().then(function (command) {
console.log("pressed: " + command.label); });
The point is that while the threading model doesn't change, when most people mention UI and threading they are thinking about logical concurrency and how it affects the programming model.
Overall I think the asynchronous paradigm shift is a positive thing. It requires a bit of a shift in perspective, but it's consistent with the way other platforms are evolving on both the client and server sides.

UpdateAllViews() from within a worker thread?

I have a worker thread in a class that is owned by a ChildView. (I intend to move this to the Doc eventually.) When the worker thread completes a task I want all the views to be updated. How can I make a call to tell the Doc to issue an UpdateAllViews()? Or is there a better approach?
Thank you.
Added by OP: I am looking for a simple solution. The App is running on a single user, single CPU computer and does not need network (or Internet) access. There is nothing to cause a deadlock.
I think I would like to have the worker thread post (or send) a message to cause the views to update.
Everything I read about threading seems way more complicated than what I need - and, yes, I understand that all those precautions are necessary for applications that are running in multiprocessor, multiuser, client-server systems, etc. But none of those apply in my situation.
I am just stuck at getting the right combination of getting the window handle, posting the message and responding to the message in the right functions and classes to compile and function at all.
UpdateAllViews is not thread-safe, so you need to marshal the call to the main thread.
I suggest you to signal a manual-reset event to mark your thread's completion and check the event's status in a WM_TIMER handler.
suggested reading:
First Aid for the Thread-Impaired:
Using Multiple Threads with MFC
More First Aid for the Thread
Impaired: Cool Ways to Take Advantage
of Multithreading

using threads and pyGST in a wx python app

OK, so I am writing an app, which plays music with the pyGST bindings.
This requires the use of threads to handle playback. The bindings library handles most of the thread control for me, which is nice(and what I was looking for in them).
Now, I don't have a full grasp on this concept, so I would be eager for some references. But the way I understand it, is I have to basically inform the app that it can use multiple threads.
I gathered this from the examples on the gstreamer site, where they use this call:
gtk.gdk.threads_init()
gtk.main()
according to here, this tells the app it can use multiple threads(more or less), which is where my above assumption came from.
That is the background. Now get this. I have placed those lines in my code, and they work fine. My app plays music rather than crashing whenever it tries. But something doesn't feel right.
In the examples that I got those lines from, they use gtk for the whole GUI, but I want to use wxWidgets, so it feels wrong calling this gtk function to do this.
Is there a wx equivalent to this? or is it ok to use this, and will it still work cross platform?
Also, I have to figure out how to kill all these threads on exit(which it does not do right now) I see how they do it in the example using a gtk method again, so again, looking for a wx equivalent.
PS: I think this(or the solution) may be related to the wx.App.MainLoop() function, but I am lost in trying to understand how this loop works, so again, good references about this would be appreciated, but I suppose not necessary as long as I have a good solution.
Try using this instead:
import gobject
gobject.threads_init()
I wonder how come it is not written in large print at the start of every python gstreamer plugin piece of documentation: it only took me several hours to find it.
A bit more details here.
I have no experience with pyGST, but the general advice for using threads and wxPython is to only update the GUI from the main thread (i.e. the thread that starts the MainLoop). See http://wiki.wxpython.org/LongRunningTasks for more information.
I have no experience with the python bindings, but I have had success using wxWidgets and GStreamer together on Windows. The problem is that wxWidgets runs a Windows event loop while GStreamer uses a GLib event loop. If you don't care about any of the GStreamer events, you shouldn't need to do anything. However, if you care to receive any of the GStreamer events, you will have to run your own GLib event loop (GMainLoop) in a separate thread with a separate GMainContext. Use gst_bus_create_watch to create a GST event source, add a callback to the source with g_source_set_callback, and then attach it to the main context of your GLib event loop with g_source_attach. You can then handle the GST in the callback, for example, to forward the events to the wx main event loop.

Resources