不同平台获取当前线程 id 的方法
- Windows
可以利用微软提供的 api,轻松获取当前线程的 id:
int id = GetCurrentThreadId();
- Linux
Linux 平台一般用的是 pthread 线程库,但它并不提供获取线程内部 id 的方法。可以通过系统调用得到当前线程的 id:
#include <unistd.h> // for syscall()
#include <sys/syscall.h> // for SYS_xxx definitions
int id = syscall(SYS_gettid);
- Mac
Mac 平台也可以用 syscall
获取当前线程的 id,与 Linux 稍有区别:
#include <unistd.h> // for syscall()
#include <sys/syscall.h> // for SYS_xxx definitions
int id = syscall(SYS_thread_selfid); // for mac os x
不过在 mac os x 10.12 之后,syscall 被标记为 deprecated,所以最好还是用下面的方法取代 syscall&