Intel® oneAPI Threading Building Blocks
Ask questions and share information about adding parallelism to your applications when using this threading library.

parallel_for creates threads that use same system thread

Dean_C_
Beginner
505 Views

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
505 Views

Hi Dean,

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

Regards,
Alex
 

0 Kudos
Dean_C_
Beginner
505 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.

0 Kudos
Alexei_K_Intel
Employee
505 Views

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

0 Kudos
Reply