在linux2.4版本后,linux使用了NPTL作为自己的线程库,为了兼容POSIX标准,所以在内核task中有两个域tgid和tid,前者是进程id,后者是线程id。在linux上获得线程id的方法,目前我所知的有三种,当然这里的三种是指在用户态的程序中,否则除非自己写的kernel module, 都是调用编号224的系统调用实现的(2.6版本)。
其中_syscall0是一个宏(由于参数的不同还有_syscall1,_syscall2...),定义如下:
#define _syscall0(type,name) \ type name(void) \ { \ long __res; \ __asm__ volatile ("int $0x80" \ //int 80, 软中断 : "=a" (__res) \ //输入输出都用的eax : "0" (__NR_##name)); \ //#define __NR_gettid 224 __syscall_return(type,__res); \ //返回tid }
#include <sysdep.h> .text ENTRY (syscall) PUSHARGS_6 /* Save register contents. */ _DOARGS_6(44) /* Load arguments. */ movl 20(%esp), %eax /* Load syscall number into %eax. */ ENTER_KERNEL /* Do the system call. */ POPARGS_6 /* Restore register contents. */ cmpl $-4095, %eax /* Check %eax for error. */ jae SYSCALL_ERROR_LABEL /* Jump to error handler if error. */ L(pseudo_end): ret /* Return to caller. */ PSEUDO_END (syscall)
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <pthread.h> #include <sys/types.h> #include <sys/syscall.h> /* must include this file */ pid_t gettid(void) { return syscall(SYS_gettid); } /* thread */ void *thread_function(void *arg) { static int i = 0; int j; i++; j = i; while (1) { printf("thread: %5u\n", gettid()); sleep(1); } } int main() { int res; pthread_t a_thread; pthread_t b_thread; void *thread_result; res = pthread_create(&a_thread, NULL, thread_function, NULL); if (res != 0) { perror("Thread creadtion failed"); exit(EXIT_FAILURE); } res = pthread_create(&b_thread, NULL, thread_function, NULL); if (res != 0) { perror("Thread creadtion failed"); exit(EXIT_FAILURE); } printf("[%d]waiting for thread to finish...\n", getpid()); pthread_join(a_thread, &thread_result); if (res != 0){ perror("Thread a join failed"); exit(EXIT_FAILURE); } printf("Thread joined, it returned %s\n", (char *)thread_result); pthread_join(b_thread, &thread_result); if (res != 0){ perror("Thread b join failed"); exit(EXIT_FAILURE); } printf("Thread joined, it returned %s\n", (char *)thread_result); exit(EXIT_SUCCESS); }
# define THREAD_SELF \ ({ struct pthread *__self; \ asm ("movl %%gs:%c1,%0" : "=r" (__self) \ : "i" (offsetof (struct pthread, header.self))); \ __self;})
原文:http://blog.chinaunix.net/space.php?uid=223060&do=blog&id=2127436