fix some possible casting issues
use __thread instead of pthread keys
fix horrible check->thread assignment bias