【问题标题】:how to get thread ID as integer on BSD in C/C++?如何在 C/C++ 中的 BSD 上将线程 ID 获取为整数?
【发布时间】:2010-10-23 13:21:56
【问题描述】:

有人知道在 BSD 上将当前线程 ID 作为整数获取吗?

我找到了这个

#ifdef RTHREADS
  299     STD     { pid_t sys_getthrid(void); }
  300     STD     { int sys_thrsleep(void *ident, int timeout, void *lock); }
  301     STD     { int sys_thrwakeup(void *ident, int n); }
  302     STD     { int sys_threxit(int rval); }
  303     STD     { int sys_thrsigdivert(sigset_t sigmask); }
#else
  299     UNIMPL
  300     UNIMPL
  301     UNIMPL
  302     UNIMPL
  303     UNIMPL
#endif

并尝试了 (long)syscall(229) 但不起作用(它崩溃了)。在 Linux 上,我可以通过系统调用 (long) syscall(224) 获取线程 ID,它给了我一个整数(通常是 4 位数字)。有人可以帮忙吗?!谢谢。

【问题讨论】:

    标签: c multithreading bsd


    【解决方案1】:

    没有“BSD”这样的东西。每个 *BSD 系统都完全不同,尤其是在线程方面。即使在像 FreeBSD 这样的单个项目中,也有各种 pthread 实现(libc_r、kse、thr),它们会因操作系统版本和用户配置而异。

    话虽如此,在 FreeBSD-8 上,/usr/include/sys/thr.h 中应该有 int thr_self(long *id),而在相当新鲜的 NetBSD 上,/usr/include/lwp.h 中应该有 lwpid_t _lwp_self(void)

    更多平台可以查看wine源码中的int get_unix_tid(void)

    【讨论】:

    【解决方案2】:

    找出哪些 可以包含在您的 C 翻译单元中(通过检查 oyur 包含路径)。 pid_t 在那里定义。它是有符号整数类型,但其中有一些。它很容易比长的更宽。

    The Open Groups documentation of sys/types.h 承诺“实现应支持一个或多个编程环境,其中 blksize_t、pid_t、size_t、ssize_t、suseconds_t 和 useconds_t 的宽度不大于 long 类型的宽度。这些编程环境的名称可以使用 confstr() 函数或 getconf 实用程序获得。”因此,您可能可以将 pid_t 转换为 long(或者至少使用 getconf 来找出在 pid_t 可以安全地转换为 long 的情况下您必须做什么)。

    请参阅C Language Gotchas: printf format strings,了解为什么您想做的事情很复杂、不能移植,并且将来可能会突然中断。

    【讨论】:

      猜你喜欢
      • 2011-11-17
      • 1970-01-01
      • 2014-02-01
      • 2021-08-14
      • 2010-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      相关资源
      最近更新 更多