gpt4 book ai didi

c - pthread_t 是为它定义的线程初始化的吗?

转载 作者:太空宇宙 更新时间:2023-11-04 00:30:42 27 4
gpt4 key购买 nike

我正在使用 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: %d\n", myInfo->thread_id);
pthread_exit(0);
}

int main() {
struct thread_info tinfo;

int s;
printf("Main thread id: %d\n", 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

关于c - pthread_t 是为它定义的线程初始化的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19691375/

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