c - 在 C 中实现 pthread_self()

标签 c pthreads

我正在尝试用 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/

相关文章:

c++ - 如何从 C 代码正确创建 DLL 并在 C++ 项目中使用它

c++ - "Sams teach yourself C"中的示例使用 "fgets"但返回错误

c++ - 为什么pthread_cond_signal会导致死锁

objective-c - 为什么在多个线程内修改NSMutableSet时崩溃,但是在同一线程内修改自定义对象Person却不会崩溃?

c - 使用线程打印全局变量

c - 在 unix 中创建和绑定(bind)端口时出现问题。 (网络编程新手)

c - 如何让 gcc 忽略从未调用过的函数?

将列表与其他列表进行比较,然后将匹配结果存储在新列表中

c - 如何在 C 中干净地终止线程?

c - 使用条件变量进行异步执行。