使用多个线程写入一个QProcess

时间:2015-09-11 12:11:40

标签: c++ multithreading qt

我有简单的程序,必须使用几个输入线程,我想编写简单的Qt-programm来测试它。 所以我用这段代码开始QProcess:

QProcess *proc = new QProcess;
proc->start("D:\\compile\\referee_system\\referee_system");
if(!proc->waitForStarted()) {
    qDebug() << "failed to start process";
    return;
}

如果我想在主线程中发送/获取数据进行处理,我可以这样做:

proc->write(reinterpret_cast<char*>(&s), sizeof(DataStruct));
proc->waitForReadyRead();
QByteArray a = proc->readAll();

但是我怎么能用几个独立的线程来写这个过程呢? 提前谢谢。

P.S。 我写了简单的测试函数:

void writeData(QProcess *p) {
    qDebug() << "writing data";
    DataStruct s;
    s.id = qrand()%2;
    s.type = START;
    for(int i = 0; i < 10; ++i)
        s.data[i] = qrand()%128;

    p->write(reinterpret_cast<char*>(&s), sizeof(DataStruct));
    p->waitForBytesWritten();
    p->waitForReadyRead();

    QByteArray a = p->readAll();

    qDebug() << a;
}

当我从主线程调用它时,没有问题,但如果我尝试使用这样的smth:

QVector<QFuture<void> > vec;

for(int i = 0; i < c_thread_count; ++i) {
    QFuture<void> f = QtConcurrent::run(writeData, proc);
    vec << f;
}

for(int i = 0; i < c_thread_count; ++i) {
    vec[i].waitForFinished();
}

我有一个错误:

QObject: Cannot create children for a parent that is in a different thread.
(Parent is QProcess(0x1549d248), parent's thread is QThread(0x13d13148), current thread is QThread(0x154dbd90)

0 个答案:

没有答案