Fixed bug in threading code