创建多线程加速处理这一段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 13:42:42 浏览: 62
可以通过使用互斥锁(mutex)来保护变量edges,确保每个线程在访问edges时都会先获得锁。具体实现如下:
1. 定义一个互斥锁
```c++
#include <mutex>
std::mutex mtx;
```
2. 创建多个线程,并在线程中访问edges前先获得锁
```c++
#include <thread>
std::vector<std::thread> threads;
for (int t = 0; t < num_threads; t++) {
threads.emplace_back([&, t]() {
for (int i = t; i < m; i += num_threads) {
std::vector<Edge1D_Result> local_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);
// 获得锁并将local_edges合并到全局变量edges中
std::lock_guard<std::mutex> guard(mtx);
edges.insert(edges.end(), local_edges.begin(), local_edges.end());
}
});
}
```
3. 等待所有线程执行完毕
```c++
for (auto& t : threads) {
t.join();
}
```
这样,就可以在多线程的情况下保护变量edges了。注意,由于需要频繁地获得和释放锁,使用过多的线程可能会导致性能下降。可以根据实际情况调整线程数量。
阅读全文