Make thread counting more robust