Optimized code. Now also returns thread's tid value.