Updating bindable property from another thread
-
According to the documentation:
Bindable properties are not threadsafe, unless stated otherwise. A bindable property must not be read or modified by any thread other than the one is was created in.
So if one needed to update the property in another thread, is the following approach valid?
class Foo : public QObject { Q_OBJECT Q_OBJECT_BINDABLE_PROPERTY(Foo, Bar, m_bar) public Q_SLOTS: void updateBar() { // Run in another thread QThreadPool::globalInstance()->start([this]{ // Fetch newBar... metaObject(this, [this, newBar] { m_bar = newBar; }, Qt::QueuedConnection); }); } }I have not faced any warning with this approach but just want to be sure.
-
It is very wasteful... why spawn a potentially new thread whose only job is schedule something on a completely different thread and immediately end?
void updateBar(Bar newBar) { QMetaObject::invokeMethod(this, [this, newBar] { m_bar = newBar }); }Should work just as well. Note that this example sticks to the default connection strategy - this way if you call
updaBarfrom the same thread asthisit will execute directly without overhead, and if you call it from another thread it will schedule the lambda for execution on the correct thread's event loop. -
It is very wasteful... why spawn a potentially new thread whose only job is schedule something on a completely different thread and immediately end?
void updateBar(Bar newBar) { QMetaObject::invokeMethod(this, [this, newBar] { m_bar = newBar }); }Should work just as well. Note that this example sticks to the default connection strategy - this way if you call
updaBarfrom the same thread asthisit will execute directly without overhead, and if you call it from another thread it will schedule the lambda for execution on the correct thread's event loop.@IgKh Thanks! Good to know that this will work.
It is very wasteful... why spawn a potentially new thread whose only job is schedule something on a completely different thread and immediately end?
It's just a simplify example. In my app, data need to be fetched from a 3rd party library in another thread to not lock up the main one, and
updateBarwould be much more complicated in actuality.Note that this example sticks to the default connection strategy - this way if you call updaBar from the same thread as this it will execute directly without overhead, and if you call it from another thread it will schedule the lambda for execution on the correct thread's event loop.
Good point! Though, when I was writing this, I only considered the need to be called in another thread, so I must have been a bit tunnel vision.