Fix threading and add some tests for it