I have an JavaFX-based application, written in Kotlin. JavaFX runs in a separate thread by default, and I want to ensure that the variable that is initialized in the main thread is ready when JavaFX reaches the part where it uses that variable.
Java has wait and notify methods that I'd use on that variable, but they aren't available in Kotlin.
I also looked into Kotlin coroutines, but they seem to be built around task dependency (i.e. one task can wait for another), but they don't work so simply with variables, and are using coroutines instead of threads, i.e. if I use coroutines to coordinate my variables, JavaFX still runs on a separate thread, which cannot be coordinated together with coroutines (or am I missing something?).
You can still use wait and notifiy in Kotlin, though not recommended.
You could also use CountDownLatch.
Related
The SDL documentation for threading states:
NOTE: You should not expect to be able to create a window, render, or receive events on any thread other than the main one.
The glfw documentation for glfwCreateWindow states:
Thread safety: This function must only be called from the main thread.
I have read about issues regarding the glut library from people who have tried to run the windowing functions on a second thread.
I could go on with these examples, but I think you get the point I'm trying to make. A lot of cross-platform libraries don't allow you to create a window on a background thread.
Now, two of the libraries I mentioned are designed with OpenGL in mind, and I get that OpenGL is not designed for multithreading and you shouldn't do rendering on multiple threads. That's fine. The thing that I don't understand is why the rendering thread (the single thread that does all the rendering) has to be the main one of the application.
As far as I know, neither Windows nor Linux nor MacOS impose any restrictions on which threads can create windows. I do know that windows have affinity to the thread that creates them (only that thread can receive input for them, etc.); but still that thread does not need to be the main one.
So, I have three questions:
Why do these libraries impose such restrictions? Is it because there is some obscure operating system that mandates that all windows be created on the main thread, and so all operating systems have to pay the price? (Or did I get it wrong?)
Why do we have this imposition that you should not do UI on a background thread? What do threads have to do with windowing, anyways? Is it not a bad abstraction to tie your logic to a specific thread?
If this is what we have and can't get rid of it, how do I overcome this limitation? Do I make a ThreadManager class and yield the main thread to it so it can schedule what needs to be done in the main thread and what can be done in a background thread?
It would be amazing if someone could shed some light on this topic. All the advice I see thrown around is to just do input and UI both on the main thread. But that's just an arbitrary restriction if there isn't a technical reason why it isn't possible to do otherwise.
PS: Please note that I am looking for a cross platform solution. If it can't be found, I'll stick to doing UI on the main thread.
While I'm not quite up to date on the latest releases of MacOS/iOS, as of 2020 Apple UIKit and AppKit were not thread safe. Only one thread can safely change UI objects, and unless you go to a lot of trouble that's going to be the main thread. Even if you do go to all the trouble of closing the window manager connection etc etc you're still going to end up with one thread only doing UI. So the limitation still applies on at least one major system.
While it's possibly unsafe to directly modify the contents of a window from any other thread, you can do software rendering to an offscreen bitmap image from any thread you like, taking as long as you like. Then hand the finished image over to the main thread for rendering. (The possibly is why cross platform toolkits disallow/tell you not to. Sometimes it might work, but you can't say why, or even that it will keep working.)
With Vulkan and DirectX 12 (and I think but am not sure Metal) you can render from multiple threads. Woohoo! Of course now you have to figure out how to do all the coordination and locking and cross-synching without making the whole thing slower than single threaded, but at least you have the option to try.
Adding to the excellent answer by Matt, with Qt programs you can use invokeMethod and postEvent to have background threads update the UI safely.
It's highly unlikely that any of these frameworks actually care about which thread is the 'main thread', i.e., the one that called the entry point to your code. The real restriction is that you have to do all your UI work on the thread that initialized the framework, i.e., the one that called SDL_Init in your case. You will usually do this in your main thread. Why not?
Multithreaded code is difficult to write and difficult to understand, and in UI work, introducing multithreading makes it difficult to reason about when things happen. A UI is a very stateful thing, and when you're writing UI code, you usually need to have a very good idea about what has happened already and what will happen next -- those things are often undefined when multithreading is involved. Also, users are slow, so multithreading the UI is not really necessary for performance in normal cases. Because of all this, making a UI framework thread-safe isn't usually considered beneficial. (multithreading compute-intensive parts of your rendering pipeline is a different thing)
Single-threaded UI frameworks have a dispatcher of some sort that you can use to enqueue activities that should happen on the main thread when it next has time. In SDL, you use SDL_PushEvent for this. You can call that from any thread.
I have read about Kotlin coroutines recently and now, I wonder what is the difference between asyncTask class and multi Thread programming and coroutines? in what situation I should use each one?
AsyncTask is abstract class and it must be subclassed. AsyncTask has 4 steps: onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
They are executed serially on single background thread.
If you want to fetch a URL or perform a heavyweight computation in Android, you have to use async programming.
they can be used when there is small task to communicate with main thread.
for tasks that use multiple instances in parallel.
Thread is a concurrent unit of execution. It has its own call stack.
With threads, the operating system switches running threads preemptively according to its scheduler.
they can be used for tasks running in parallel use Multiple threads.
for task where you want to control the CPU usage relative to the GUI thread.
Coroutines use to write asynchronous code that will look like normal sequential code.
they can provide a very high level of concurrency with very little overhead.
They are simple to read, unlike thread they are lightweight and unlike AsyncTask lot of them can run at same time.
AsyncTask was the first hand solution proposed by Google in Android SDK in order to process work in the background, while keeping the main thread free from many complex operations. In fact, AsyncTask let you to do complex processing in an asynchronous manner. Compared to classical Java Thread, the AsyncTask was somehow specialized, providing UI wrappers around threads in order to allow a more enjoyable experience as a developer, coding in an async way. The AsyncTask class was deprecated in the meantime and the recommended way to solve things is by using coroutines.
Coroutines are not a new concept introducer by Kotlin, in fact this concept exists in a lot of programming languages (Go has Goroutines and Java will provide something called Fibers). The main advantage of using coroutines is the simplicity of code, the only thing that differentiate a sync task/function in face of an async task/function is the usage of suspend keyword put in front of the function.
For example, the following function is executed in a synchronous way:
fun doSomething() = println("Print something")
while the following one is executed on a asynchronous way, due to the usage of suspend keyword:
suspend fun doSomething() = println("Print something")
When a suspend function is reached, the program will not block there, and will go further in running the rest of the code, but will receive a Continuation which will return the value computed by the suspended function when this one will be available.
Can a function be forced to be called in a separate thread using Corona SDK?
How?
edit:
So what I felt was slacking down my system was not depending on asynchronous calls. It was a table view that had to be filled with 1000+ elements. Turns out, it was a bug in an earlier version of corona SDK. Updating to the latest build made the table-view row insertion much more rapid.
The closest you can get in Lua (and Corona SDK) is coroutines but these are not really threads but rather (to quote Programming in Lua):
A coroutine is similar to a thread (in the sense of multithreading): a
line of execution, with its own stack, its own local variables, and
its own instruction pointer; but sharing global variables and mostly
anything else with other coroutines. The main difference between
threads and coroutines is that, conceptually (or literally, in a
multiprocessor machine), a program with threads runs several threads
concurrently. Coroutines, on the other hand, are collaborative: A
program with coroutines is, at any given time, running only one of its
coroutines and this running coroutine only suspends its execution when
it explicitly requests to be suspended.
http://www.lua.org/pil/9.html
Unfortunately, if you approach coroutines hoping that they will be like threads you'll be disappointed.
I know that you need synchronize (yourprocedure) to set e.g. a label's text.
But what about:
Reading a label's text.
Toggle/Set the label's enabled property.
Call other labels procedures/functions (e.g. onclick event).
Is there an easy rule to know/remember when I need to use synchronize?
PS.: Is synchronize similar to PostMessage/SendMessage?
Easy rule of thumb: ANY access to VCL UI components needs to be synchronized. That includes both reading and writing of UI control properties. Win32 UIs, most notably dialogs like MessageBox() and TaskDialog(), can be used directly in worker threads without synchronizing.
TThread.Synchronize() is similar to SendMessage() (in fact, it used to be implemented using SendMessage() internally in Delphi 5 and earlier). TThread.Queue() is similar to PostMessage().
Any time you access a VCL UI component, you need to implement some type of thread safety measure. This is also, typically, the case when you're accessing a variable or procedure that exists or will be accessed by another thread. However, you don't need to use the Synchronize method in all of these situations. There are other tools at your disposal, and Synchronize is not always your best solution.
Synchronize blocks both the main thread and the calling thread while it's performing the procedure that you pass to it, so overusing it can detract from the benefits of multi-threading. Synchronize is probably most commonly used for updating your UI, but if you find that you're having to use it really frequently, then it might not be a bad idea to check and see if you can restructure your code. I.E. do you really need to read labels from within your thread? Can you read the label before starting the thread and pass it into the thread's constructor? Can you handle any of these tasks in the thread's OnTerminate event handler?
I have wp7 app whith two background threads:
1. Planing of time
2. Play different sound samples by planed time (Possible few samples in same time).
How to repeat this logic whith unity3d engine? Is it possible?
Unity will not allow you to access its APIs from any thread other than the main one; you can't use locking primitives to get around it.
You can use the standard .NET threading APIs to start threads that do not interact directly with the Unity API, though. You could calculate samples and buffers on an extra thread, but your main thread would have to call AudioClip.SetData to submit the calculated samples to Unity.
Note that since Unity 2018.1, the Job System has been introduced which allows certain kinds of computation tasks to be performed on background threads (for example, setting transform positions). The tasks that can be performed are being gradually opened up over time.
The fact that the API is not threadsafe does not mean that you cannot use it with additional thread safety. You only need to ensure that no two threads modify the common data at the same time. You can use a simple lock variable to ensure no one reads the samples list while it is being updated.
However, instead of threads I'd recommend using coroutines, because they make things a lot easier. No thread safety is needed, the benefits are similar and the execution order is way clearer.
A simpler way to achieve a similar solution would be to update the samples list inside Update, and read it in a LateUpdate method.
No way =( Unity API is not threadsafe: link