【问题标题】:Qt get a threads ID in the main thread?Qt在主线程中获取线程ID?
【发布时间】:2012-03-01 08:29:51
【问题描述】:

我对此有一些疑问:

首先我创建我的对象并将它移动到一个线程:

FileUploader *fileUploader = new FileUploader(fileList_, start, (offset == 0 ? (fileList_.count() - start) : offset));
QThread *fileUploaderThread = new QThread;
fileUploader->moveToThread(fileUploaderThread);

fileUploaderThreads_.append(fileUploaderThread);
fileUploaders_.append(fileUploader); // contains pointers to the objects

connect(fileUploader, SIGNAL(progressChangedAt(int)), model_, SLOT(reportProgressChanged(int)), Qt::QueuedConnection);
connect(fileUploader, SIGNAL(statusChangedAt(int)), model_, SLOT(reportStatusChanged(int)), Qt::QueuedConnection);
connect(fileUploader, SIGNAL(finished()), fileUploaderThread, SLOT(quit()), Qt::QueuedConnection);
connect(fileUploaderThread, SIGNAL(finished()), this, SLOT(checkIfFinished()), Qt::QueuedConnection);

插槽中的 checkIfFinished() 我想检查所有线程,看看它们是否退出。 qDebug()

foreach(QThread *thread, fileUploaderThreads_) { // or FileUploader* fileuploader, fileUploaders_ ?
    if(thread && !thread->isFinished()) {

        qDebug() << "not finished " << thread->currentThreadId();

        return; // not done
    }
}

当它被打印出来时,我只得到主线程 ID,而不是线程。我试图打印线程ID,但没有运气(在它们启动后)。 我这样做的原因是因为编写“高级 Qt 编程 - Mark S”的人对 QThreads 做了类似的事情,他将其放在列表中并检查它们是否完成。现在唯一起作用的是在 fileUploader 完成时终止线程的连接。

另外,我如何存储线程的指针?如果它们似乎没有指向正确的线程,我将如何将它们全部删除。

编辑:

我尝试将 QObjects 存储在一个列表中,然后这样做:

QThread *senderx = qobject_cast<QThread*>(sender());

qDebug() << "one thread done" << senderx;

foreach(FileUploader *fileUploader, fileUploaders_) {
    if(fileUploader && !fileUploader->thread()->isFinished()) {

        qDebug() << "not finished " << fileUploader->thread();

        return; // not done
    }
}
//done 
qDebug() << "done";
setButtonState(false);

我最后一次通话的结果是:

一个线程完成 QThread(0x43ee180)

未完成 QThread(0x43ee180)

这怎么可能?它完成了,但方法却另有说明。

【问题讨论】:

    标签: c++ multithreading qt


    【解决方案1】:

    你想要QObject::thread(),而不是QThread::currentThreadId() - 第二个返回调用函数的线程。

    一旦你解决了这个问题,你的指针就会正常工作。

    【讨论】:

    • 那行得通。但是我的程序似乎并没有因为某种原因每次运行时都完成。
    • 在您的编辑中,它是什么函数(在什么对象中),它是从哪里调用的?如果您愿意,我们可以用它来聊天。
    • 函数是“checkIfFinished”。是的,当然
    • 不知道能不能直接邀请你,不过我开了个房间叫Qt Threading Discussion
    • 该函数将返回执行调用的线程的 id - 意思是,您需要从 within 该线程调用它,而不是 on i> 那个线程(它是QThreadstatic 方法,因此它根本不作用于 对象)。在您的情况下,您可以在FileUploader 中有一个插槽并通过排队连接访问它 - 这样调用将在作用于FileUploader 对象的线程的事件循环中执行。
    猜你喜欢
    • 2010-12-13
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多