Fix for #1811 , might be improved.
More fixes for #1811.
Fixes for thread safety, issue #1811
Merge pull request #2387 from eliangidoni/fix-1811

Fix for #1811 by @eliangidoni, reviewed by @danielmewes.