C语言 pthread_t 为定义它的线程初始化



我正在使用pthread_t打印出我在 C 中手动创建的线程的 pid。 但是,我在创建新线程之前打印它(通过 ref 作为参数传递它),它打印一个不同的值(大概是我的主函数正在执行的线程)。 我本来希望它默认为 0 或单位化。 有什么想法吗?谢谢

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
struct thread_info {    /* Used as argument to thread_start() */
    pthread_t thread_id;/* ID returned by pthread_create() */
};
static void *thread_1_start(void *arg) {
    struct thread_info *myInfo = arg;
    printf("Started thread id: %dn", myInfo->thread_id);
    pthread_exit(0);
}
int main() {
    struct thread_info tinfo;
    int s;
    printf("Main thread id: %dn", tinfo.thread_id);
    s = pthread_create(&tinfo.thread_id,
        NULL, // was address of attr, error as this was not initialised.
        &thread_1_start,
        &tinfo);
    pthread_join(tinfo.thread_id,NULL);
}

实际输出:

Main thread id: 244580352
Started thread id: 245325824

预期产出:

Main thread id: // 0 or undefined
Started thread id: 245325824

问题是您没有初始化tinfo结构。

局部变量(与全局/堆变量相反)中,值不会在 C 编程语言中初始化。

因此,如果您执行以下操作:

int c;
printf("%d", c);

您不应该期望一个连贯的值,因为它将取决于当时该内存位置上的内容。

您需要初始化tinfo变量。使用 memset 或显式分配tinfo.thread_id = 0

没有特定于线程的逻辑来初始化tinfo;它只是一个常规的C结构。它将具有初始化时该内存地址中的任何数据。您需要显式初始化它。

您可以通过以下方式将值初始化为零:

struct thread_info tinfo = { 0 };

声明struct thread_info tinfo;全局,看看会发生什么。

您需要了解许多重要事项。

首先,pthread_t是不透明的。你不能用printf可靠地打印它,因为POSIX标准中没有任何地方pthread_t指定为beinban in,struct或其他任何东西。根据定义,您无法打印它并获得有意义的输出。

其次,如果线程需要知道它是pthread_t ID,它可以调用 pthread_self()。你不需要告诉线程它的 ID 在外部是什么,就像你试图做的那样。

但没关系!您描述的打印输出接近预期的情况是因为您在线程打印输出和将pthread_t分配给 thread_info.thread_id pthread_create之间存在竞争,并且由于pthread_t实际上是 Linux 上的整数类型(因此它们很可能是按顺序分配的,而您只是得到一个旧值)。

最新更新