How to do async file io in qt?

末鹿安然 提交于 2019-12-12 08:16:04

问题


I was wondering how to achieve async file io in qt? Is this even achievable in vanilla qt or would someone need to use another library (libuv for example) to achieve something like this? I was looking at QDataStream but even though it is a "stream" it isn't non blocking. I guess one solution would be to make a custom QIODevice that uses libuv internally which can then be used with QDataStream but not sure where to start. Any ideas?

Thanks for any help provided.


回答1:


I would implement a thread that will handle the I/O. You can connect the appropriate sig/slots to "invoke" the IO from your main thread to the IO thread. You can pass the data to be read/written as a parameter to the signal. Something like this:

class FileIOThread : public QThread
{
public: 
    void run();
public slots: 
    void writeData(QByteArray &)
    void readData(QByteArray &)
};

class MyClass
{
private:
    FileIOThread m_writerThread;
signals: 
    void sendData(QByteArray &);
 ....
};

MyClass::MyClass()
{
    connect(this, SIGNAL(sendData(QByteArray&)),
                  &m_writerThread,SLOT(writeData(QByteArray&)));
   ....
 }


来源:https://stackoverflow.com/questions/13677834/how-to-do-async-file-io-in-qt

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