我正在尝试用 C 实现 pthread_self()
但我对它到底做了什么感到困惑。我知道它返回线程 ID,但该 ID 是一个内存位置,因为它返回一个我不确定如何解释的 pthread_t
。另外,我将如何检索线程的 id,我是否只是创建一个新线程并返回它?
最佳答案
pthread_self() 返回线程的 ID。请检查 pthread_self 和 pthread_create 的手册页。
man 3 pthread_self
man 3 pthread_create
对于 pthread_create(),第一个参数的类型为 pthread_t。它被分配新创建的线程的ID。该 ID 用于识别其他 pthread 函数的线程。 pthread_t 的抽象类型取决于实现。
Before returning, a successful call to pthread_create() stores the ID of the new thread in the buffer pointed to by thread; this identifier is used to refer to the thread in subsequent calls to other pthread functions.
pthread_self 返回与 pthread_create 在第一个参数“thread”中存储的 ID 相同的 ID
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
pthread_t pthread_self(void);
在我的系统中,pthread_t 类型是“unsigned long int”
/usr/include/x86_64-linux-gnu/bits/pthreadtypes.h:typedef unsigned long int pthread_t;
在以下示例中,pthread_self() 和 th1 返回的值相同。
// main function:
pthread_t th1;
if(rc1 = pthread_create(&th1, NULL, &functionC1, NULL))
{
printf("Thread creation failed, return code %d, errno %d", rc1, errno);
}
printf("Printing thread id %lu\n", th1);
// Thread function:
void *functionC1(void *)
{
printf("In thread function Printing thread id %lu\n", pthread_self());
}
Output:
Printing thread id 140429554910976
In thread function Printing thread id 140429554910976
请查看博客Tech Easy有关线程的更多信息。
关于c - 在 C 中实现 pthread_self(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52657858/