我想使用OpenMP并行化一个for循环(我之前使用std :: threads完成了它,但是这个解决方案相当丑陋),但是它的条件可能会在每次迭代时发生变化。 这是我的意思的例子:
#pragma omp parallel for
for(int i = 0; i < someVector.size(); i++)
{
. . .
if(something)
someVector.push_back(v);
}
然而,这不起作用。循环似乎与初始someVector.size()值一样。有没有办法在OpenMP中并行化这样的结构?
答案 0 :(得分:2)
此代码不符合要求:for语句不具有规范要求的规范形式,可以使用#pragma omp parallel for
进行注释({3}的第2.6节})。
问题在于条件表达式:规范声明如果条件表达式的格式为i relational-op expr
,expr
必须是循环不变表达式,并且代码不满足此约束
答案 1 :(得分:0)
OpenMP plotly
了解for循环中的条件。它知道它迭代从0到某个最大值的数字,因此它在开始时评估最大值,然后将工作分成几个线程。如果循环执行期间的最大变化,则不起作用。
进一步修改sample <- data.frame(
Category <- c("Furniture","Furniture","Furniture","Furniture",
"Office Supplies","Office Supplies", "Office Supplies", "Office Supplies",
"Office Supplies", "Office Supplies", "Office Supplies", "Office Supplies",
"Office Supplies", "Technology","Technology","Technology","Technology"),
SubCategory <- c("Bookcases","Chairs","Furnishings","Tables","Appliances","Art","Binders","Envelopes",
"Fasteners","Labels","Paper","Storage", "Supplies", "Accessories","Copiers","Machines",
"Phones"),
sales <- c(889222.51,920892.65,239840.16,445823.93,614737.91,225594.68,281494.68,104903.88,50156.06,44269.30,
150113.36,692903.08,152196.19,463383.33,965899.78,458655.43,1005525.38)
)
sample %>%
plot_ly(
x = SubCategory,
y = sales,
type = "bar",
group = Category)
而其他一些线程正在使用它绝对不是安全的操作。您会得到未定义的行为,可能是因为在向量移动存储的数据后访问释放的内存而崩溃。
您可以使用某些线程安全队列替换#pragma omp for
。然后,您可以自由地弹出并推送使用多个工作程序的值。