我正在使用 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