I use tbb::parallel_for quite a lot, but then I ran into an issue running our program on a AWS server. It would throw an exception in a mutex saying it was already locked. On my local system, I printed out what the Windows thread id is for each thread used by the parallel_for, and some threads had the same id. Yikes! Why does it do this?
Anyway, I thought maybe I would try a recursive mutex, and if I detect the recursion, then I could do something, like a call to Sleep. Well, my recursive mutex indeed caught the recursion, but Sleep didn't work. So how do I get the other thread to complete?
Note, there is no actual recursion going on here, as far as I can tell. I'm thinking that when parallel_for has multiple threads using the same system id, that that means those multiple threads may collide with each other in my mutexed code. A while back I even saw this on a debug stack trace that it had called my parallel_for code recursively on the same thread.
Is this supposed to happen? How are mutexes supposed to work in such conditions?
Ah, so nested parallel_for loops can cause the outer loop to effectively recurse using the same system thread, and so one needs to use the tbb isolate construct to get around this:
// Parallel work
} // The guard_lock will be released here automatically that is safe in case of exception.
Thanks, I'll give this a try, since I do indeed have nested loops in my case.