【发布时间】:2015-10-08 09:35:35
【问题描述】:
已经在一些 OpenCV 函数上创建了 C++ 包装器并将其导出到 PInvoke,可以并行调用它。
说实话:
void execute(Document& d) {
ScriptConfig conf(d);
Context c(conf);
OperationManager m;
while (c.next()) {
unique_ptr<OperationBase> op = m.create(*c.getCurrentOp());
// m.create inside ALWAYS creates unique_ptr<OperationBase>(NEW ConcreteOperationBase());
//nothing cached
op->prepare(&c);
op->execute();
op->afterExecute();
}
}
内部操作使用它的上下文并在 OpenCV 中执行一些操作。 Context 保存 Mat 的操作实例。
此代码不是线程安全的。如果我尝试使用几个执行 emmidiatly 调用,它们会以随机方式破坏彼此的工作。看起来操作的输入->输出垫无效。
我在操作中检查了与 opencv 相关的代码是否是线程安全的 - 没关系。
当我通过以下方式修复它时:
mutex _locker;
无效执行(文档& d){
ScriptConfig conf(d);
Context c(conf);
OperationManager m;
while (c.next()) {
_locker.lock();
unique_ptr<OperationBase> op = m.create(*c.getCurrentOp());
// m.create inside ALWAYS creates unique_ptr<OperationBase>(NEW ConcreteOperationBase());
//nothing cached
op->prepare(&c);
op->execute();
op->afterExecute();
_locker.unlock();
}
}
不,多线程没有问题。但这不是我想要的——我必须并行调用操作!
【问题讨论】:
-
你能找出不同的线程是否同时使用相同的输入/输出吗?每个输入/输出使用一个互斥锁或确保线程不共享它们。
标签: c++ multithreading opencv