linux - 如何为 pthreads 中的锁定互斥锁获取拥有线程的线程 ID

标签 linux multithreading pthreads posix mutex

一个线程有一个类型为pthread_mutex_t 的互斥体为它自己锁定。另一个线程想知道持有这个锁定互斥锁的线程的线程 ID。

据我了解,线程 ID 有两种类型。 pthread_self() 返回的 POSIX/pthread 线程 id,以及系统调用 gettid() 返回的 linux 线程 id。这两个是独立的,没有关系,AFAIK(如果我错了请纠正我)。

pthread_mutex_t结构体中有一个字段,int __owner,存放当前持有锁的线程的线程id。可以通过以下方式访问此字段,

pthread_mutex_t mutex;
int tid;
tid = mutex.__data.__owner;

如此处所述 - Is it possible to determine the thread holding a mutex? .

__owner 字段具有 linux 系统线程 ID(如 gettid() 返回)而不是 POSIX/pthread 线程 ID(如由 gettid() 返回) pthread_self()) .

我想比较当前调度的线程是否拥有互斥体。所以,我应该将 pthread_self()__owner 值进行比较。

我可以使用 gettid() 而不是 pthread_self(),但我只能使用 pthread_self()。 (一些可移植性功能)。

有什么方法可以正确确定将返回 pthread_t 而不是系统线程 ID 的锁定互斥体的线程 ID?

我将不胜感激任何帮助,谢谢!

问候,

优素福侯赛尼。

最佳答案

1)

These two are independent and have no relation, AFAIK (please correct me If I am wrong).

没错。来自 man pthread_self:

The thread ID returned by pthread_self() is not the same thing as the kernel thread ID returned by a call to gettid(2).

2)

so, I should be comparing pthread_self() with the __owner value

这是不正确的,man pthread_self:

Thread identifiers should be considered opaque: any attempt to use a thread ID other than in pthreads calls is non-portable and can lead to unspecified results.

3)

Is there any way to correctly determine the thread id of the locked mutex which would return pthread_t and not the system thread id?

我想,没有。 pthread_mutex_t 具有字段 int __owner; 并且没有像 pthread_owner 这样包含线程的 pthread_t 的字段:

/* Data structures for mutex handling.  The structure of the attribute
   type is not exposed on purpose.  */
typedef union
{
  struct __pthread_mutex_s
  {
    int __lock;
    unsigned int __count;
    int __owner;
#if __WORDSIZE == 64
    unsigned int __nusers;
#endif
    /* KIND must stay at this position in the structure to maintain
       binary compatibility.  */
    int __kind;
#if __WORDSIZE == 64
    int __spins;
    __pthread_list_t __list;
# define __PTHREAD_MUTEX_HAVE_PREV      1
#else
    unsigned int __nusers;
    __extension__ union
    {
      int __spins;
      __pthread_slist_t __list;
    };
#endif
  } __data;
  char __size[__SIZEOF_PTHREAD_MUTEX_T];
  long int __align;
} pthread_mutex_t;

关于linux - 如何为 pthreads 中的锁定互斥锁获取拥有线程的线程 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25500440/

相关文章:

c - 具有连接文件描述符的 pthread 竞争条件

java - 如何从 jni 端调用 java 方法?

linux - shell 脚本无法进入包含空格的目录

multithreading - 如何使对象(可变堆栈)线程安全?

php - 用户 apache 无法访问其拥有的文件

multithreading - 如何使用 GNU Parallel 编写多核排序

c - 线程创建过程中程序执行的流程

c++ - 一个生产者,两个消费者作用于生产者产生的一个 'queue'

regex - 我怎样才能执行这个grep命令

linux - 重命名每个组中的最新文件