pthread的结构如下。它取自 https:/stuff.mit.eduafssipbprojectpthreadsincludepthread.h。
struct pthread {
struct machdep_pthread machdep_data;
enum pthread_state state;
pthread_attr_t attr;
/* Signal interface */
sigset_t sigmask;
sigset_t sigpending;
/* Time until timeout */
struct timespec wakeup_time;
/* Cleanup handlers Link List */
struct pthread_cleanup *cleanup;
/* Join queue for waiting threads */
struct pthread_queue join_queue;
/* Queue thread is waiting on, (mutexes, cond. etc.) */
struct pthread_queue *queue;
/*
* Thread implementations are just multiple queue type implemenations,
* Below are the various link lists currently necessary
* It is possible for a thread to be on multiple, or even all the
* queues at once, much care must be taken during queue manipulation.
*
* The pthread structure must be locked before you can even look at
* the link lists.
*/
struct pthread *pll; /* ALL threads, in any state */
/* struct pthread *rll; Current run queue, before resced */
struct pthread *sll; /* For sleeping threads */
struct pthread *next; /* Standard for mutexes, etc ... */
/* struct pthread *fd_next; For kernel fd operations */
int fd; /* Used when thread waiting on fd */
semaphore lock;
/* Data that doesn't need to be locked */
void *ret;
int error;
const void **specific_data;
};
typedef struct pthread * pthread_t;
现在让我们看看下面的代码来打印线程的ID。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* calls(void* ptr)
{
// using pthread_self() get current thread id
printf("In function \nthread id = %ld\n", pthread_self());
pthread_exit(NULL);
return NULL;
}
int main()
{
pthread_t thread; // declare thread
pthread_create(&thread, NULL, calls, NULL);
printf("In main \nthread id = %ld\n", thread);
pthread_join(thread, NULL);
return 0;
}
在我的系统中的输出是:
In main
thread id = 140289852200704
In function
thread id = 140289852200704
从pthread.h文件(上图)看,pthread是一个结构。thread
中的指针,指向结构pthread(因为 pthread_t
是 typdef struct pthread*
). 为什么打印这个指针会给我们线程ID呢?
从pthread.h文件(上面)来看,pthread是一个结构。
thread
中的指针,指向结构pthread(因为pthread_t
是typdef struct pthread*
).
要明确的是。在这种情况下, pthread_t
是一个指向结构的指针类型。 我想这在pthreads的实现中是很常见的,但是要注意避免将某一实现的细节误认为是规范或所有实现的一般特征。 例如,它也可能是其他实现中的一个整数索引,以及其他各种可能性。
为什么打印这个指针会给我们线程ID呢?
因为它 是 的线程ID。而且因为你很幸运,打印它时产生的未定义行为与 %d
格式化指令在两个地方的表现方式是一样的。
你可能已经给自己造成了伤害,因为你在实现的 pthread_t
. 你不需要知道这些细节就可以使用pthreads,事实上它们对你没有丝毫帮助。 类型是要被当作不透明的。
要回答这个问题,你真正需要了解的是,写进变量 thread
由 pthread_create()
是创建的线程的ID,由 pthread_self()
是调用线程的线程ID。 当然,每个获取线程ID的机制都会为同一个线程产生相同的ID。