【发布时间】:2013-11-10 13:33:40
【问题描述】:
我正在使用 pthread_t 打印出我在 C 中手动创建的线程的 pid。但是,我在创建新线程之前打印它(通过 ref 作为参数传递它)并打印不同的值(大概我的 main 函数正在执行的线程)。我本来希望它默认为 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
【问题讨论】:
-
还可以查看this 以更好地了解线程 ID。
标签: c multithreading pthreads pid