Alican
Alican

Reputation: 286

invoking methods that work on main thread

I have two different threads. the first one is the main thread that must handle the gui operations. the second one is a network thread which listens the related tcp ports. I need network thread to invoke methods in a way that they will run in the main thread. how can I achieve this without using a message queue mechanism?

Upvotes: 2

Views: 1238

Answers (2)

user406009
user406009

Reputation:

How I would do it in your case is to is tell the other thread to schedule a function on its event queue. Arguments to that function are bound in with the function that is sent.

Like for example in the network code:

int result = doWork();
otherThreadsEventLoop.scheduleFunction(drawResult,result);

All GUI frameworks and most networking frameworks allow you to do that.

  • If you are using qt, then QMetaObject::invokeMethod is what you would use.
  • If you are using gtk, then q_idle_add is what you would use.
  • If you are using boost::asio, then io_service.post is what you would use.
  • If you are using libevent, then event_base_once is what you would use.

One issue might be the binding of additional parameters for libraries that only give you C callbacks. My suggestion is to write a "wrapper" function that allows you to pass std::functions into the callback.

Upvotes: 3

bames53
bames53

Reputation: 88225

You have to tell the code running on the main thread that it needs to call your methods. No matter how you implement this you will essentially have some kind of message queue. You'll have to be more specific about your actual requirements so that we can suggest a message queue mechanism appropriate for your case.

Upvotes: 2

Related Questions