UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » Threads
  • » how to tell a second thread to execute a method of main thread ?

#1 2012-12-24 03:37 PM

jackleung
Member
Registered: 2012-11-30
Posts: 2

how to tell a second thread to execute a method of main thread ?

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)

Offline

#2 2012-12-24 09:03 PM

Nope
Administrator
From: Germany
Registered: 2004-01-24
Posts: 385
Website

Re: how to tell a second thread to execute a method of main thread ?

That depends.

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?

Offline

#3 2012-12-25 03:14 AM

jackleung
Member
Registered: 2012-11-30
Posts: 2

Re: how to tell a second thread to execute a method of main thread ?

Nope wrote:

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.

Offline

#4 2012-12-27 08:29 AM

Nope
Administrator
From: Germany
Registered: 2004-01-24
Posts: 385
Website

Re: how to tell a second thread to execute a method of main thread ?

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.

Offline

  • Index
  • » Threads
  • » how to tell a second thread to execute a method of main thread ?

Board footer

Powered by FluxBB