connectedComponentsWithStats Problem in Multithread
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.
did you find a note anywhere, that this funcion would be threadsafe ?
@berak the threads have their own variables. Can't find any issues with the thread itself. I usually use functions in threads unless the doc warn me. So you think this function isn't threadsafe? What is the solution? Do you recommend using a mutex lock for connectedComponentsWithStats?
no, the function itself might not be threadsafe to use. (it's also using parallel_for_ already internally)
@berak To me it looks like a bad design. Because connectedComponentsWithStats can be used frequently in parallel programs. I might have to create a thread-safe function for running connectedComponentsWithStats.
@berak What is the solution when using parallelized OpenCV functions in different threads? I had the same problem a few days ago.
@kbarni, yes, i've seen it ;(
@milad, the devs assume , you don't use multithreading (and so they're allowed to do weird optimization tricks, that might break your code)
you can try to disable the internal optimizations, but i somehow doubt, that doing this, and using your own multithreading on top of it is the right way to go, at all.
sorry, i don't have an easy or concise answer.