https://gcc.gnu.org/bugzilla/show_bug.cgi?id=119136
--- Comment #8 from Andre Vehreschild <vehre at gcc dot gnu.org> --- Jerry, may be you can use an atomic https://gcc.gnu.org/wiki/Atomic . This way you don't need an expensive lock. My strategy would be to declare a global atomic bool value (e.g. in_output) and in each __gfortran_st_write() do <code>if (!__atomic_test_and_set(&in_output) { runtime_error("nested_IO"); }</code>. And in the __gfortran_st_write_done() just a <code>__atomic_clear(&in_output);</code>. This should already catch 99% of all cases. Just an idea, I am curious of what you come up with...