Fixed threading bugs