1

I'm looking for a way to implement a functional equivalent of invokeOnMainThread(c# xamarin)/ runOnUiThread(android)/ performSelectorOnMainThread:(objective C) in C/C++ on linux.

Essentially what I need is a function, which can be called from any thread, to which I pass a handler, which is executed on the main thread.

I believe this will be helpful in cases where I want to restrict access to a particular resource to a particular thread (eg. libmysql DB access to main thread).

What would be an elegant way to implement this? How is it done in android?

Zaxter
  • 2,939
  • 3
  • 31
  • 48
  • 1
    In C++, how about a [container](http://en.cppreference.com/w/cpp/container) with [functions](http://en.cppreference.com/w/cpp/utility/functional/function) that the wanted thread just calls? In C it's easy to implement something similar with a simple linked list and function pointers. – Some programmer dude Feb 10 '15 at 14:27
  • 2
    Thjis requirement needs some kind of signaling to other threads - something that the 'main thread' frequently waits on for input messages/objects/function pointers/lambadas/whatever. If the 'main thread' does implement some kind of message-handling loop, (as in many GUI systems), you can do it. If not, you cannot, because the 'normal' stack-based function call/return mechanism cannot change thread context. – Martin James Feb 10 '15 at 14:36
  • 1
    In addition to what is pointed out above, what is your "main thread" doing already? Are you using some kind of application framework? If you're just looking for the ability to queue up handlers to execute on a particular thread, then one almost-off-the-shelf way would be to use C++ Boost.ASIO to create a thread pool with only a single thread. You can then post handlers to it as needed and they will all get executed on the desired thread. – Jason R Feb 10 '15 at 14:48
  • Thanks Joachim, Martin and Jason, for your suggestions. I'm currently looking at POSIX Msg queues. I'll pass the handlers as messages and have the main thread periodically retrieve and call them. – Zaxter Feb 10 '15 at 14:57

1 Answers1

1

It is straightforward to have your runOnMainThread function place handlers in a thread-safe queue for later execution by the main thread. Your main thread needs to be prepared to periodically execute handlers it finds in that queue. This implies that the main thread needs to include a loop that periodically checks for new handlers in the queue. This periodic checking can be made efficient through the use of semaphores or other thread-safe signaling mechanisms.

Here are some SO questions on thread safe queues:

Community
  • 1
  • 1
Randall Cook
  • 6,728
  • 6
  • 33
  • 68