c++ - Qt signal argument thread safety -


suppose have signal sendimage(const qimage&) connected slot updatelabel(const qimage&) in other thread, convert qimage qpixmap place in qlabel. i'm wondering, if use function const qimage& prepareimage() argument of signal e.g. emit sendimage(prepareimage()), , signal emitted dozens of times per seconds, thread safe or there possibility race condition occurs between prepareimage , updatelabel both accessing image @ same time crashing program?

thankfully, qt protects , copy image don't shoot in foot. copying done upon signal's emission, , done inside of implementation of signal - here, copying done when object::source on call stack.

given qimage implicitly shared, initial copy cheap, if main thread modifies source image, force deep copy. if modifications such source discarded, it'll more efficient replace source image new 1 instead of "modifying" it.

output:

data @ 0x7fff5fbffbf8 in main thread qthread(0x10250a700) 0x7fff5fbffbf8 copied 0x1025115d0 in thread qthread(0x10250a700) got 0x1025115d0 in thread qthread(0x7fff5fbffb80) 
#include <qcoreapplication> #include <qdebug> #include <qthread>  class copyable { public:    copyable() {}    copyable(const copyable & src) {       qdebug() << static_cast<const void*>(&src) << "was copied to"                << static_cast<void*>(this) << "in thread" << qthread::currentthread();    } }; q_declare_metatype(copyable)  class object : public qobject {    q_object public:    q_signal void source(const copyable &);    q_slot void sink(const copyable & data) {       qdebug() << "got" << static_cast<const void*>(&data) << "in thread"                << qthread::currentthread();       // queue quit since racing app.exec(). qapp->quit() no-op before       // app.exec() has had chance block.       qmetaobject::invokemethod(qapp, "quit", qt::queuedconnection);    } };  class thread : public qthread { public: ~thread() { quit(); wait(); } };  int main(int argc, char *argv[]) {    qcoreapplication app(argc, argv);    copyable data;    qdebug() << "data at" << static_cast<void*>(&data) << "in main thread" << app.thread();    qregistermetatype<copyable>();    object o1, o2;    thread thread;    o2.movetothread(&thread);    thread.start();    o2.connect(&o1, &object::source, &o2, &object::sink);    emit o1.source(data);    return app.exec(); }  #include "main.moc" 

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -