您的位置:首页 > 运维架构 > Linux

Linux用户空间线程管理介绍之一

2015-05-19 15:55 471 查看
转自:http://www.longene.org/forum/viewtopic.php?f=17&t=414

线程不管是在Windows还是在Linux中都是一个很重要的概念。在Windows应用中,多线程程序是相当的普遍,要让这些应用在Linux下能顺利的运行,必须在兼容内核中增加对Windows线程的支持,而这个,一定是离不开Linux线程的支持。
Linux线程由Linux内核、glibc和libpthread这三种共同支持。在当前的兼容内核版本中,已经充分考虑到了Linux内核中对线程的支持,但是在用户空间,也就是glibc和libpthread中对现场的支持,我们并没有在ntdll.dll或kernel32.dll中进行相应的处理。因此,有必要对glibc和libpthread中线程相关数据结构进行分析,并将其加入到ntdll.dll或kernel32.dll中。
在用户空间,和线程关系比较密切的,应该有那么几块:
一是类似于线程控制块(TCB)的数据结构,在用户空间中代表着一个线程的存在;
二是线程私有堆栈,
三是线程局部数据(TLS);
在多线程程序中,各个线程直接的大部分数据都是共享的,不过上述三者都是不共享的。这三种数据位于同一块内存中,是在创建线程的时候,用mmap系统调用分配出来的,要访问这块地址,需要通过gs寄存器,对于同一个进程内的每一个线程,gs寄存器指向的地址都是不一样的,这样可以保证各个进程之间不会相互干扰。
这三块数据在内存分布上,大概如下:
-----------
pthread
-----------
TLS
-----------
Stack
-----------
上面说到,这块内存通过gs寄存器访问,那么gs寄存器指向这块地址的哪个地方呢?是指向pthread结构的首地址。下面来看一下pthread结构:
123 /* Thread descriptor data structure. */
124 struct pthread
125 {
126 union
127 {
128 #if !TLS_DTV_AT_TP
129 /* This overlaps the TCB as used for TLS without threads
(see tls.h). */
130 tcbhead_t header;
131 #else
132 struct
133 {
134 int multiple_threads;
135 int gscope_flag;
136 # ifndef __ASSUME_PRIVATE_FUTEX
137 int private_futex;
138 # endif
139 } header;
140 #endif
141

142 /* This extra padding has no special purpose, and this structure
layout
143 is private and subject to change without affecting the official
ABI.
144 We just have it here in case it might be convenient for some
145 implementation-specific instrumentation hack or suchlike.
*/
146 void *__padding[16];
147 };
148

149 /* This descriptor's link on the `stack_used' or `__stack_user'
list. */
150 list_t list;
151

152 /* Thread ID - which is also a 'is this thread descriptor
(and
153 therefore stack) used' flag. */
154 pid_t tid;
155

156 /* Process ID - thread group ID in kernel speak. */
157 pid_t pid;
158

159 /* List of robust mutexes the thread is holding. */
160 #ifdef __PTHREAD_MUTEX_HAVE_PREV
161 void *robust_prev;
162 struct robust_list_head robust_head;
......
197 #else
198 union
199 {
200 __pthread_slist_t robust_list;
201 struct robust_list_head robust_head;
202 };
......
231 #endif
......
235 /* List of cleanup buffers. */
236 struct _pthread_cleanup_buffer *cleanup;
237

238 /* Unwind information. */
239 struct pthread_unwind_buf *cleanup_jmp_buf;
......
241

242 /* Flags determining processing of cancellation. */
243 int cancelhandling;
......
276 /* Flags. Including those copied from the thread attribute.
*/
277 int flags;
278

279 /* We allocate one block of references here. This should
be enough
280 to avoid allocating any memory dynamically for most applications.
*/
281 struct pthread_key_data
282 {
283 /* Sequence number. We use uintptr_t to not require padding
on
284 32- and 64-bit machines. On 64-bit machines it helps to avoid
285 wrapping, too. */
286 uintptr_t seq;
287

288 /* Data pointer. */
289 void *data;
290 } specific_1stblock[PTHREAD_KEY_2NDLEVEL_SIZE];
291

292 /* Two-level array for the thread-specific data. */
293 struct pthread_key_data *specific[PTHREAD_KEY_1STLEVEL_SIZE];
294

295 /* Flag which is set when specific data is set. */
296 bool specific_used;
297

298 /* True if events must be reported. */
299 bool report_events;
300

301 /* True if the user provided the stack. */
302 bool user_stack;
303

304 /* True if thread must stop at startup time. */
305 bool stopped_start;
306

307 /* The parent's cancel handling at the time of the pthread_create
308 call. This might be needed to undo the effects of a cancellation.
*/
309 int parent_cancelhandling;
310

311 /* Lock to synchronize access to the descriptor. */
312 int lock;
313

314 /* Lock for synchronizing setxid calls. */
315 int setxid_futex;
316

317 #if HP_TIMING_AVAIL
318 /* Offset of the CPU clock at start thread start time. */
319 hp_timing_t cpuclock_offset;
320 #endif
321

322 /* If the thread waits to join another one the ID of the
latter is
323 stored here.
324

325 In case a thread is detached this field contains a pointer
of the
326 TCB if the thread itself. This is something which cannot
happen
327 in normal operation. */
328 struct pthread *joinid;
329 /* Check whether a thread is detached. */
330 #define IS_DETACHED(pd) ((pd)->joinid == (pd))
331

332 /* The result of the thread function. */
333 void *result;
334

335 /* Scheduling parameters for the new thread. */
336 struct sched_param schedparam;
337 int schedpolicy;
338

339 /* Start position of the code to be executed and the argument
passed
340 to the function. */
341 void *(*start_routine) (void
*);

342 void *arg;
343

344 /* Debug state. */
345 td_eventbuf_t eventbuf;
346 /* Next descriptor with a pending event. */
347 struct pthread *nextevent;
348

349 #ifdef HAVE_FORCED_UNWIND
350 /* Machine-specific unwind info. */
351 struct _Unwind_Exception exc;
352 #endif
353

354 /* If nonzero pointer to area allocated for the stack and
its
355 size. */
356 void *stackblock;

357 size_t stackblock_size;
358 /* Size of the included guard area. */
359 size_t guardsize;
360 /* This is what the user specified and what
we will report. */
361 size_t reported_guardsize;
362

363 /* Thread Priority Protection data. */
364 struct priority_protection_data *tpp;
365

366 /* Resolver state. */
367 struct __res_state res;
368

369 /* This member must be last. */
370 char end_padding[];
......
374 } __attribute ((aligned (TCB_ALIGNMENT)));
header:结构一开始是一个union,据我观察,在用过的好多个系统中,TLS_DTV_AT_TP宏均为0,也就是说,一开始就是一个tcbhead_t结构的头部,tcb应该就是Thread
Control Block(线程控制块)的缩写。这个结构灯会介绍。
list:双向队列的连接件,用来将这个结构连接到stack_cached或者stack_used队列中,大家或许奇怪,这个是pthread结构,不是堆栈,为什么连接到stack_cached或stack_cached队列中,其实,堆栈、TLS和pthread结构都是不可分的,他们是同一块内存,这样使用也是很正常的。
tid、pid:线程号和进程号。有一点需要注意的是,在单线程的情况下,虽然初始线程也有pthread结构,但并不对这两个字段进行赋值,只有在getpid调用的时候,才会对tid赋值,pid好像一直为0,除非加载了libpthread(不管是显式还是隐式),pid才可能赋值。
mutex相关:160-231行之间的字段,和pthread_mutex相关,不做介绍。
cleanup、cleanup_jmp_buf:和线程退出的善后工作相关;
cancelhandling:和线程取消相关;
specific、specific_1stblock:和线程键(pthread_key)相关,我在以前使用的时候,经常使用这个结构来存放一些线程的私有数据,但我不知道和TLS有什么关系,是不是可以用TLS来代替,有兴趣者可以查看现有的多线程编程资料。
result:存放线程start_routine的返回值。
schedparam、schedpolicy:和线程调度策略有关。
start_routine:入口函数;
arg:传给入口函数的参数;
stackblock:指向堆栈;
stackblock_size:堆栈大小;
guardsize:guard页大小,这个页面和普通堆栈页面有着不同的访问权限,其权限为PROT_NONE,也就是无法访问,位于堆栈的最底端,用来警示堆栈溢出,因为访问到这个页面的时候,就会引起一个page
fault。
reported_guardsize:用来向用户程序报告guard页的大小。

下面介绍一下tcbhead_t结构,如下:
typedef struct
{
void *tcb; /* Pointer to the TCB. Not necessarily the
thread descriptor used by libpthread. */
dtv_t *dtv;
void *self; /* Pointer to the
thread descriptor. */
int multiple_threads;
uintptr_t sysinfo;
uintptr_t stack_guard;
uintptr_t pointer_guard;
} tcbhead_t;
这个结构中,最常用的就是self字段了,它指向pthread结构的首地址,前面提到过,gs寄存器指向pthread结构的首地址,所以可以通过下面的汇编指令,获取pthread结构的首地址:
asm volatile ("movl %%gs:0x8, %0" : "=r"(pd));
gs:0x8就是获取gs指向地址偏移8个字节处的内容,刚好是self字段。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: