Why does this code sometimes (maybe 5% of the times) return "5 4" instead of "5 5"? connectedComponentsWithStats should be executed inside 5 threads but sometimes one of them ruins things.
// std::atomic<int> first = 0, last = 0;
ThreadPool pool(thread::hardware_concurrency()); // 2 threads
for (int i = 0; i < 5; i++) {
pool.enqueue([i, binaryImg] { // Add the thread.
first++;
Mat labels, stats, centroids;
int objCount = connectedComponentsWithStats(binaryImg, labels, stats, centroids, 8); // PROBLEM. Sometimes the following lines inside this block won't be executed.
last++;
});
}
pool.~ThreadPool(); // Join all the threads.
cout << first << ' ' << last << endl;
Is there any problem with connectedComponentsWithStats when used in multiple threads? A weird problem to me because it gives no errors.