0
votes

I am creating a TaskScheduler, which schedules a handler at give time-duration and execute it when timer expires. Under the hood, it is using asio::deadline_timer. As per the documentation of asio::io_service, the handler will be invoked in the thread context where io_server::run() function is running. While my requirement is to call handler in different thread context.

How can we achieve it? Precisely my question is that, How can we execute a function in different thread context. E.g. I am current in Thread1 but from Thread1, I want to run some function from Thread2 context.

Thanks

1
The question has nothing to do with Boost Asio, I suggest you remove that part. You need to pass a message between threads. Simplest "message" would be a [condition variable}en.cppreference.com/w/cpp/thread/condition_variable) (or "event"). For practical intents and purpose, most often a (blocking) queue is used - sehe

1 Answers

0
votes

A common pattern is

  • the client thread requests a timer callback (bind parameters) and goes to sleep
  • the timer expires and the callback is executed in the context of the timer thread
  • the callback does post a command into the clients queue
  • the client thread wakes up and executes the command

the timer thread is completely decoupled from the client implementation (queue handling). the client must behave cooperative i. e. do not stress the callback time but return immediately.