使用多线程加速处理这一段for循环vector<Edge1D_Result>edges;for (int i = 0; i < m; i++) { edges = Extract1DEdgeCircle.Get1DEdge(RoiMat, m_vpdEquinoxPoints[i], m_dMeasureLength, m_dMeasureHeight, m_vdMeasureAngle[i] , m_dSigma, m_nThresholdCircle, m_nTranslationCircle == 1 ? Translation::Poisitive : Translation::Negative, Selection::Strongest); for (int i = 0; i < edges.size(); i++) { m_vpdEdgePoints.push_back(edges[i].m_pdEdgePoint); m_vdEdgeGradient.push_back(edges[i].m_dGradient); } }保护变量edges
时间: 2023-12-10 08:40:30 浏览: 95
edges-master.rar_7FN_Edge Boxes_wnn_检测仿真_边缘检测
可以使用C++11的std::mutex来保护变量edges,确保多个线程不会同时访问和修改它。
首先,在头文件中包含<mutex>:
```c++
#include <mutex>
```
然后,在定义vector<Edge1D_Result>edges之前,定义一个全局的std::mutex对象:
```c++
std::mutex mtx;
```
接下来,在for循环中对edges的访问和修改需要加锁和解锁:
```c++
for (int i = 0; i < m; i++) {
std::vector<Edge1D_Result> temp_edges;
temp_edges = Extract1DEdgeCircle.Get1DEdge(RoiMat, m_vpdEquinoxPoints[i], m_dMeasureLength, m_dMeasureHeight, m_vdMeasureAngle[i] , m_dSigma, m_nThresholdCircle, m_nTranslationCircle == 1 ? Translation::Poisitive : Translation::Negative, Selection::Strongest);
// 加锁
mtx.lock();
for (int i = 0; i < temp_edges.size(); i++) {
m_vpdEdgePoints.push_back(temp_edges[i].m_pdEdgePoint);
m_vdEdgeGradient.push_back(temp_edges[i].m_dGradient);
}
mtx.unlock(); // 解锁
}
```
在加锁之前,我们需要定义一个临时的vector<Edge1D_Result>来存储Extract1DEdgeCircle.Get1DEdge()函数返回的结果,以免因为加锁时间过长导致函数返回的结果被覆盖。
这样做可以确保多个线程不会同时访问和修改变量edges,从而避免了数据竞争和意外的结果。
阅读全文