【发布时间】:2018-09-04 11:40:06
【问题描述】:
我是新手,如果这篇文章发错地方了,请告诉我。
我正在尝试在我的程序中将线程用于“for 循环”,但根据我的研究,model->setData 与线程不兼容。
所以我的解决方案是:
我将在每个线程和 at 中使用不同的模型,并将它们合并为一个以显示在 tableview 中。
但是我不熟悉Qt所以我有点卡在这里我不知道如何将两个模型相互合并,你能检查我的代码吗?
{
t2 = std::thread{[&]{
const auto row_size = (RegexOperations_.indexed_arranged_file.size()
const auto col_size = RegexOperations_.indexed_arranged_file[0].size();
for(unsigned int i = 0 ; i < (row_size+1) / 2) ; i++)
{
for(unsigned int j = 0 ; j < col_size;j++)
{
std::string temp = RegexOperations_.indexed_arranged_file[i][j];
QModelIndex index = model ->index(i,j,QModelIndex());
model->setData(index,temp.c_str());
}
}
}};
//t3 = std::thread{[&]{
// const auto row_size = (RegexOperations_.indexed_arranged_file.size()
// const auto col_size = RegexOperations_.indexed_arranged_file[0].size();
// for(unsigned int i = (row_size+1) / 2) ; i < row_size;i++)
// {
// for(unsigned int j = 0 ; j < col_size;j++)
// {
// std::string temp = RegexOperations_.indexed_arranged_file[i][j];
// QModelIndex index = model ->index(i,j,QModelIndex());
// model->setData(index,temp.c_str());
// }
// }
//}};
t2.join();
//t3.join();
const auto tvr = ui->tableView_results;
tvr->setModel(model);
tvr->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
tvr->setEditTriggers(QAbstractItemView::NoEditTriggers);
}
感谢您的帮助...
【问题讨论】:
-
欢迎来到 SO。请查看meta.stackexchange.com/help/how-to-ask,了解如何提出一个好问题。我认为我们在这里遇到了 XY 问题en.wikipedia.org/wiki/XY_problem。为什么要使用线程?
-
我的问题是“你的问题到底是什么?”到目前为止,代码看起来还不错(您在两个线程之间拆分工作。现在您需要合并模型。您遇到了什么问题?您确定多线程循环值得为合并模型付出代价吗?
-
首先感谢您的评论。我的问题是我不能对模型使用互斥锁,因为它不是线程安全的,它会减慢很多,所以我的解决方案是合并模型我该怎么做?
-
模型实际上是模型数据的外观,是模型数据的便捷前端。您需要一种方法来合并模型本身的 数据,而不是合并 models。这是你的 XY 问题。 =)
-
嗯,这就是你的 XY 问题的一半。上面提到的另一半 Michael:你真的需要线程这些操作吗?