Fix thread safety issues in dynamic_lib

The root issue is that dlerror isn't reentrant or even thread safe.

The Windows code isn't affected since errno is thread-local on Windows
and it's running in an atomically block to ensure there isn't a green
thread context switch.

Closes #8156