Re: How to update both the Console and the GTKMM gui window after running other functions
- From: Andrew Potter <agpotter gmail com>
- To: Alan Mazer <alan s mazer jpl nasa gov>
- Cc: "gtkmm-list gnome org" <gtkmm-list gnome org>
- Subject: Re: How to update both the Console and the GTKMM gui window after running other functions
- Date: Thu, 1 Aug 2013 10:09:27 -0700
On Thu, Aug 1, 2013 at 9:52 AM, Alan Mazer <alan s mazer jpl nasa gov> wrote:
P.S. I don't know why it doesn't take arguments either, but one can work
around that with globals and a mutex.
There's actually a really nice solution I've been using lately. It
uses C++11, but it can be rewritten using only glib/sigc++.
class CallbackDispatcher {
public:
CallbackDispatcher(const CallbackDispatcher&) = delete;
CallbackDispatcher& operator=(const CallbackDispatcher&) = delete;
CallbackDispatcher() {
m_dispatcher.connect(sigc::mem_fun(*this,
&CallbackDispatcher::on_dispatch));
};
template<typename Fn>
void operator()(Fn&& fn) {
std::lock_guard<std::mutex> lock(m_mutex);
m_msgs.push(std::forward<Fn>(fn));
m_dispatcher();
}
private:
typedef std::function<void ()> Callback;
std::queue<Callback> m_msgs;
mutable std::mutex m_mutex;
Glib::Dispatcher m_dispatcher;
void on_dispatch() {
std::lock_guard<std::mutex> lock(m_mutex);
while (!m_msgs.empty()) {
m_msgs.front()();
m_msgs.pop();
}
}
};
Usage:
void my_fun(Param one, Param two) {
// Whatever should be run in main loop
}
void my_threaded_fun() {
// This is running on a separate thread
Param one, two;
callbackDispatcher(std::bind(&my_fun, one, two));
// The bound function is added to the callback_dispatchers queue, the
dispatcher is called. In the main loop eventually the queue is served
and the callback is called with the bound parameters!
}
What's nice about this pattern is that you only need one dispatcher
for any number of callbacks.
Also its nice to just throw a lambda in there..
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]