fix build and functionality on FreeBSD

This pull request includes several commits:
* Fix includes

pthread_yield() and arguments of clock_gettime() need these
* Fix qsort_r

FreeBSD's qsort_r() is
`void qsort_r(void *base, size_t nmemb, size_t size, void *thunk, int (*compar)(void *, const void *, const void *));`
while Linux's is
`void qsort_r(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *, void *), void *arg);`
Both the prototype of qsort_r() and the comparison function's prototype are different.
* Fix thread id

FreeBSD does not have gettid syscall, use pthread_self() instead.