Community
cancel
Showing results for 
Search instead for 
Did you mean: 
Dean_C_
Beginner
57 Views

parallel_for creates threads that use same system thread

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?

Thanks.

0 Kudos
3 Replies
Alexei_K_Intel
Employee
57 Views

Hi Dean,

Could you consider the answer on a similar question, please? Does it relate to the observed issue?

Regards,
Alex
 

Dean_C_
Beginner
57 Views

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:

tbb::this_task_arena::isolate(
    [] {
        guard_lock lock(mutex);
        // 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.

Alexei_K_Intel
Employee
57 Views

Additional information can be found in the blog article about work isolation.

Reply