Emitting QVector reference in Qt signal results in copy

落爺英雄遲暮 提交于 2019-12-06 10:20:55

Copies will be made in this case both because you are passing by value and because signals across thread boundaries are queued. That's fine though, because implicit-sharing means they are shallow copies. There's practically no overhead to copying if both the original and the copy are only used for reading.

Unfortunately, that's not actually the case in your program. Your forever loop will modify the vector when it loops back around after signal emission. In this example, it won't actually change anything in the vector since you're always just assigning 1,2,3,4, but calling the non-const operator[] is enough to trigger the deep copy.

My conclusion is this: you can be synchronous and share the same buffer between your readers and writers, or you can be asynchronous and give a copy of your write buffer to your readers. You cannot be asynchronous and share the same buffer between your readers and your writers.

The way you're handling this seems fine for asynchronous processing. Depending on the characteristics of your data generation and data processing, you may (or may not) find a synchronous solution to be better. The easiest way to make your asynchronous code synchronous is to supply the connection type as Qt::BlockingQueuedConnection on connect.

To answer your second question, you can create a multiple inheritance with QObject to your QRunnable (just make sure that QObject is always the first in the list). You can then pass your data around using the signal/slot mechanism exactly the same way you are in your test example.

class DataProcessor : public QObject, public QRunnable
{ Q_OBJECT
public:

public slots:
   void processBlock(QVector<unsigned short>);
};

Actually, you could use this structure for your Acquire class as well since your aim is to run code in a different thread, not add extra features to the thread itself.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!