2

I put together a C++ 11 based callback timer class based on the help I got on SO on this thread.

Now what I would like to do is have this thread post a message to the main thread to call a particular function. So the func() call in the timer class should happen in the main thread rather than the current thread.

This is similar to the Qt signal/slot mechanism where the signal can happen in another thread but the flow gets executed in the thread of the receiver object. Is this possible with the C++ 11 mechanisms?

Community
  • 1
  • 1
Luca
  • 10,458
  • 24
  • 107
  • 234
  • 1
    What's wrong with exactly what you described? Have a message queue that your timer thread posts messages to, and your main thread polls from? –  May 25 '15 at 10:25
  • 1
    Have a look at Boost.Asio. `io_service::post(func)` will call `func` from the thread you called `io_service::run` with, which sounds exactly like what you want in 1 line of code. It also has [timers](http://www.boost.org/doc/libs/1_58_0/doc/html/boost_asio/tutorial/tuttimer2.html) – Slyps May 25 '15 at 10:30
  • How is the main thread polling work in this context? – Luca May 25 '15 at 10:41
  • Unfortunately boost is not an option in this project – Luca May 25 '15 at 10:41
  • 2
    Use a thread safe queue implementation like the following https://juanchopanzacpp.wordpress.com/2013/02/26/concurrent-queue-c11/ to post back to the main thread. Create the queue in the main thread and pass it to the child. Then the main thread will try to `pop` from the queue, waiting on a condition variable until the child thread `push`es a message onto the queue. – Paul Rooney May 25 '15 at 11:32
  • 1
    You have to solve the [producer-consumer problem](https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem). This inevitably has a major impact on how the "main thread" is structured. It is however universal in any GUI app. – Hans Passant May 25 '15 at 12:59

0 Answers0