APUE-線程:pthread_create的實現與apue2的區別

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>


void printf_id(const char *name)
{
	pid_t pid, ppid;
	pthread_t tid;
	pid = getpid();
	ppid = getppid();
	tid = pthread_self();
	printf("%s pid = %d  ppid = %d tid = %u ox%x\n", name, pid, ppid, tid, tid);
}

void *pthread_proc(void *arg)
{
	printf_id("new pthread");
	pthread_exit((void*)NULL);
}

int main(int argc, char **argv)
{
	pthread_t tid;
	int err;
	err = pthread_create(&tid, NULL, pthread_proc, NULL);
	if(err != 0)
	{
		printf("pthread_create :%s\n", strerror(err));
		return -1;
	}
	printf_id("main pthread");
	err = pthread_join(tid, (void *)NULL);
	if(err != 0)
	{
		printf("pthread_join :%s\n", strerror(err));
		return -1;
	}
	return 0;
	
}


./a.out (執行結果如下)
main pthread pid = 25368  ppid = 17795 tid = 3069550592 oxb6f5a000
new pthread pid = 25368  ppid = 17795 tid = 3068322928 oxb6e2e470


疑問:
        觀察程序執行結果,與apue2上面所描述的Linux下執行結果有兩點差別:

      o 這裏兩個線程的pid相同(說明是同一個進程)
        而書中所敘述的是:Linux使用clone系統調用來實現pthread_create,clone用於創建
        子進程。按書所說,主線程和新線程的pid應該不同(書上的結果確實是不同pid)。

      o Linux裏pthread_t實現爲unsigned long int,但這裏打印出來的線程ID值看起來十六
        進制的表示更有意義些,這是爲何?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章