PDA

View Full Version : QtConcurrent locking



MTK358
20th September 2010, 03:23
I have a QtConcurrent function that manipulates list items that can become deleted at any time. I made in if statement to check if the item is NULL, but the problem is that it could switch to another thread and delete the item right after the if. How do I stop this?

tbscope
20th September 2010, 06:38
Well obviously you want to create a lock on the list so only one thread can change it, and release the lock when done.

But, I guess with a little bit of redesigning it might be possible without a lock. But you need to provide more details about the list, the threads, what they contain, what they do, your algorithms etc...

MTK358
20th September 2010, 12:22
void MainWindow::getThumbnail(QStandardItem *item)
{
if (item != NULL) {
item->setData(QImage(item->data(MainWindow::ImagePathRole).toString()).scaled (64, 64), Qt::DecorationRole);
}
}

void MainWindow::onDirViewActivated(QModelIndex index) // if this is called again before the thumbnail functions end, it will segfault.
{
qDebug() << dirTreeModel->data(index).toString();
QDirIterator i("/home/michael/Pictures", QDir::Files); // fix this to use the selected dir
imageListModel->clear();
while (i.hasNext()) {
i.next();
QStandardItem *item = new QStandardItem(i.fileName());
item->setData(i.filePath(), ImagePathRole);
QtConcurrent::run(getThumbnail, item);
imageListModel->appendRow(item);
}
}

wysota
20th September 2010, 13:04
You cannot operate on QStandardItem objects from within threads.

MTK358
20th September 2010, 13:10
What to do then?

wysota
20th September 2010, 13:12
Return the image from the concurrent function and use QFuture interface to set it onto the item in the main thread.

MTK358
20th September 2010, 16:23
how do I do that when I'll call QtConcurrent::run possibly hundreds of times before one of them finishes?

wysota
20th September 2010, 16:43
Store QFuture objects within your model (or anywhere else you want).

MTK358
3rd October 2010, 03:12
Why do QFutures contain lists (I thought that the concurrent function returns one value)?

wysota
3rd October 2010, 13:35
There are variations of QtConcurrent calls that operate on containers and process each container element in separate threads.