# Why is it not a good idea to branch a thread outside of a parallel region while other threads are still executing?

Say I have $$n$$ threads executing in a parallel region and one of them leaves the parallel region when others are still continuing to execute in the parallel region. Why this is a $$BAD$$ idea? For example you can consider this program.

$OMP PARALLEL IF(EXECUTE==true) 10 sum(id)=next(id) 30 result(id)=sum(id)*9.8 if(converged(result(id)) goto 20 go to 10$SOMP END PARALLEL
if(not_FINISHED) goto 30

20 print *,id


In this code we are branching out of the parallel region. I have read that its a $$BAD$$ idea to do so, but I have not got the reason. So it will be very helpful if someone can shed some light on this.

• Please don't use mathmode as a way to highlight words; this is a typographic nightmare. – Watercrystal Oct 28 '20 at 9:35
• Does stackoverflow.com/a/17394580/7092484 answer your question? – Throckmorton Oct 28 '20 at 18:00
• @Throckmorton I have seen that answer, but I am looking for a more detailed explanation. That answer only gives an overview. – Turing101 Oct 28 '20 at 20:55
• Please include in the question what research you've done and what you've found and explain why it didn't meet your needs. If you already know of an answer and you didn't understand it, please link to that answer and explain what you did understand and what you didn't understand. Otherwise, we risk repeating something that you already know isn't working for you. Thank you. – D.W. Oct 31 '20 at 19:28

## 1 Answer

OS functions are called to create and join a thread.

The main thread waits for all created thread to return (join). When a thread jump out in middle, the main thread will wait infinitely. In the example you have given one of the spawned thread jumps to a location in main thread. It will proceed and the program will eventually end. Any thread can exit/close the program. It may be the case that other spawned threads are in different stages of their execution and since parent (main) thread has exited, they will terminate inflight as well.

A lot of resources allocated to the abruptly terminated threads by OS, will waste. A properly terminated thread releases all the resources allocated to it properly, improperly terminated threads won't.