You are not logged in.
I have a method_a in main thread, and a second thread, say second_thread.
In second_thread, how to tell the main thread to execute method_a ?
Last edited by jackleung (2012-12-24 03:38 PM)
If the main thread just sits there waiting for the second thread to finish something, you could let it wait in a semaphore that's set free by the second one.
If the main thread does other things, you could raise an event, with a handler for it registered in the main thread. Or, raise a signal, what's basically the same.
You could use shared memory and let the main thread check it in intervals. That does work, but you'll have a delay, depending on the cycle.
A somewhat easier thing would be to just create a third thread. Is there any reason it must be the original main thread?
Is there any reason it must be the original main thread?
No. I am studying the Cocoa programming on MacOS, then I meet this method "performSelectorOnMainThread:withObject:waitUntilDone:". I just want to know how it works.
That's MacOS/Cocoa specific. As it is there necessary to ensure that especially UI updates are performed by the main thread (else a lot bad things happen).
I am not really sure how this could be replicated using other languages in other OSes. Basically the main thread would have to be interrupted, run the code and then go back where it came from. I am not really into MAC programming. One solution would be for the main thread waiting anyway to be called by an event. Then it'll just run the code and go back to waiting again. This could be done using Pipes and a blocking wait. Where the Pipe would deliver the reverences to execute the task at hand.
As I've said before, in other OSes, where it doesn't matter which thread updates the UI or loads data and such, I'd just create a new thread to handle these things asynchronously.