gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:37:04 26 4
gpt4 key购买 nike

一个线程有一个类型为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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com