首页 > 代码库 > pthread_create

pthread_create

//\glibc-2.24\sysdeps\nptl\pthread.h
/*
Create a new thread, starting with execution of START-ROUTINE getting passed ARG. Creation attributed come from ATTR. The new handle is stored in *NEWTHREAD. */ extern int pthread_create (pthread_t *__restrict __newthread, const pthread_attr_t *__restrict __attr, void *(*__start_routine) (void *), void *__restrict __arg) __THROWNL __nonnull ((1, 3));

参数类型:

/* Thread identifiers.  The structure of the attribute type is not
   exposed on purpose.  */
typedef unsigned long int pthread_t;


union pthread_attr_t
{
  char __size[__SIZEOF_PTHREAD_ATTR_T];
  long int __align;
};

函数实现,路径:\glibc-2.24\nptl\pthread_create.c

versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);

函数的内部参数类型:

//\glibc-2.24\nptl\descr.h
/* Thread descriptor data structure.  */
struct pthread
{
  union
  {
#if !TLS_DTV_AT_TP
    /* This overlaps the TCB as used for TLS without threads (see tls.h).  */
    tcbhead_t header;
#else
    struct
    {
      /* multiple_threads is enabled either when the process has spawned at
     least one thread or when a single-threaded process cancels itself.
     This enables additional code to introduce locking before doing some
     compare_and_exchange operations and also enable cancellation points.
     The concepts of multiple threads and cancellation points ideally
     should be separate, since it is not necessary for multiple threads to
     have been created for cancellation points to be enabled, as is the
     case is when single-threaded process cancels itself.

     Since enabling multiple_threads enables additional code in
     cancellation points and compare_and_exchange operations, there is a
     potential for an unneeded performance hit when it is enabled in a
     single-threaded, self-canceling process.  This is OK though, since a
     single-threaded process will enable async cancellation only when it
     looks to cancel itself and is hence going to end anyway.  */
      int multiple_threads;
      int gscope_flag;
# ifndef __ASSUME_PRIVATE_FUTEX
      int private_futex;
# endif
    } header;
#endif

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

  /* This descriptor‘s link on the `stack_used‘ or `__stack_user‘ list.  */
  list_t list;

  /* Thread ID - which is also a ‘is this thread descriptor (and
     therefore stack) used‘ flag.  */
  pid_t tid;

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

  /* List of robust mutexes the thread is holding.  */
#ifdef __PTHREAD_MUTEX_HAVE_PREV
  void *robust_prev;
  struct robust_list_head robust_head;

  /* The list above is strange.  It is basically a double linked list
     but the pointer to the next/previous element of the list points
     in the middle of the object, the __next element.  Whenever
     casting to __pthread_list_t we need to adjust the pointer
     first.  */
# define QUEUE_PTR_ADJUST (offsetof (__pthread_list_t, __next))

# define ENQUEUE_MUTEX_BOTH(mutex, val)                            do {                                              __pthread_list_t *next = (__pthread_list_t *)                        ((((uintptr_t) THREAD_GETMEM (THREAD_SELF, robust_head.list)) & ~1ul)          - QUEUE_PTR_ADJUST);                                  next->__prev = (void *) &mutex->__data.__list.__next;                  mutex->__data.__list.__next = THREAD_GETMEM (THREAD_SELF,                                       robust_head.list);              mutex->__data.__list.__prev = (void *) &THREAD_SELF->robust_head;              THREAD_SETMEM (THREAD_SELF, robust_head.list,                             (void *) (((uintptr_t) &mutex->__data.__list.__next)                           | val));                            } while (0)
# define DEQUEUE_MUTEX(mutex)   do {                                              __pthread_list_t *next = (__pthread_list_t *)                        ((char *) (((uintptr_t) mutex->__data.__list.__next) & ~1ul)                 - QUEUE_PTR_ADJUST);                                  next->__prev = mutex->__data.__list.__prev;                          __pthread_list_t *prev = (__pthread_list_t *)                        ((char *) (((uintptr_t) mutex->__data.__list.__prev) & ~1ul)                 - QUEUE_PTR_ADJUST);                                  prev->__next = mutex->__data.__list.__next;                          mutex->__data.__list.__prev = NULL;                              mutex->__data.__list.__next = NULL;                            } while (0)
#else
  union
  {
    __pthread_slist_t robust_list;
    struct robust_list_head robust_head;
  };

# define ENQUEUE_MUTEX_BOTH(mutex, val)                            do {                                              mutex->__data.__list.__next                                    = THREAD_GETMEM (THREAD_SELF, robust_list.__next);                  THREAD_SETMEM (THREAD_SELF, robust_list.__next,                             (void *) (((uintptr_t) &mutex->__data.__list) | val));       } while (0)
# define DEQUEUE_MUTEX(mutex)   do {                                              __pthread_slist_t *runp = (__pthread_slist_t *)                        (((uintptr_t) THREAD_GETMEM (THREAD_SELF, robust_list.__next)) & ~1ul);     if (runp == &mutex->__data.__list)                                THREAD_SETMEM (THREAD_SELF, robust_list.__next, runp->__next);              else                                            {                                              __pthread_slist_t *next = (__pthread_slist_t *)                    (((uintptr_t) runp->__next) & ~1ul);                          while (next != &mutex->__data.__list)                            {                                              runp = next;                                      next = (__pthread_slist_t *) (((uintptr_t) runp->__next) & ~1ul);       }                                                                                    runp->__next = next->__next;                              mutex->__data.__list.__next = NULL;                            }                                            } while (0)
#endif
#define ENQUEUE_MUTEX(mutex) ENQUEUE_MUTEX_BOTH (mutex, 0)
#define ENQUEUE_MUTEX_PI(mutex) ENQUEUE_MUTEX_BOTH (mutex, 1)

  /* List of cleanup buffers.  */
  struct _pthread_cleanup_buffer *cleanup;

  /* Unwind information.  */
  struct pthread_unwind_buf *cleanup_jmp_buf;
#define HAVE_CLEANUP_JMP_BUF

  /* Flags determining processing of cancellation.  */
  int cancelhandling;
  /* Bit set if cancellation is disabled.  */
#define CANCELSTATE_BIT        0
#define CANCELSTATE_BITMASK    (0x01 << CANCELSTATE_BIT)
  /* Bit set if asynchronous cancellation mode is selected.  */
#define CANCELTYPE_BIT        1
#define CANCELTYPE_BITMASK    (0x01 << CANCELTYPE_BIT)
  /* Bit set if canceling has been initiated.  */
#define CANCELING_BIT        2
#define CANCELING_BITMASK    (0x01 << CANCELING_BIT)
  /* Bit set if canceled.  */
#define CANCELED_BIT        3
#define CANCELED_BITMASK    (0x01 << CANCELED_BIT)
  /* Bit set if thread is exiting.  */
#define EXITING_BIT        4
#define EXITING_BITMASK        (0x01 << EXITING_BIT)
  /* Bit set if thread terminated and TCB is freed.  */
#define TERMINATED_BIT        5
#define TERMINATED_BITMASK    (0x01 << TERMINATED_BIT)
  /* Bit set if thread is supposed to change XID.  */
#define SETXID_BIT        6
#define SETXID_BITMASK        (0x01 << SETXID_BIT)
  /* Mask for the rest.  Helps the compiler to optimize.  */
#define CANCEL_RESTMASK        0xffffff80

#define CANCEL_ENABLED_AND_CANCELED(value) \
  (((value) & (CANCELSTATE_BITMASK | CANCELED_BITMASK | EXITING_BITMASK                     | CANCEL_RESTMASK | TERMINATED_BITMASK)) == CANCELED_BITMASK)
#define CANCEL_ENABLED_AND_CANCELED_AND_ASYNCHRONOUS(value) \
  (((value) & (CANCELSTATE_BITMASK | CANCELTYPE_BITMASK | CANCELED_BITMASK               | EXITING_BITMASK | CANCEL_RESTMASK | TERMINATED_BITMASK))        == (CANCELTYPE_BITMASK | CANCELED_BITMASK))

  /* Flags.  Including those copied from the thread attribute.  */
  int flags;

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

    /* Data pointer.  */
    void *data;
  } specific_1stblock[PTHREAD_KEY_2NDLEVEL_SIZE];

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

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

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

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

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

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

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

  /* Lock for synchronizing setxid calls.  */
  unsigned int setxid_futex;

#if HP_TIMING_AVAIL
  /* Offset of the CPU clock at start thread start time.  */
  hp_timing_t cpuclock_offset;
#endif

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

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

  /* The result of the thread function.  */
  void *result;

  /* Scheduling parameters for the new thread.  */
  struct sched_param schedparam;
  int schedpolicy;

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

  /* Debug state.  */
  td_eventbuf_t eventbuf;
  /* Next descriptor with a pending event.  */
  struct pthread *nextevent;

  /* Machine-specific unwind info.  */
  struct _Unwind_Exception exc;

  /* If nonzero pointer to area allocated for the stack and its
     size.  */
  void *stackblock;
  size_t stackblock_size;
  /* Size of the included guard area.  */
  size_t guardsize;
  /* This is what the user specified and what we will report.  */
  size_t reported_guardsize;

  /* Thread Priority Protection data.  */
  struct priority_protection_data *tpp;

  /* Resolver state.  */
  struct __res_state res;

  /* This member must be last.  */
  char end_padding[];

#define PTHREAD_STRUCT_END_PADDING \
  (sizeof (struct pthread) - offsetof (struct pthread, end_padding))
} __attribute ((aligned (TCB_ALIGNMENT)));
//\glibc-2.24\sysdeps\nptl\internaltypes.h
struct pthread_attr
{
  /* Scheduler parameters and priority.  */
  struct sched_param schedparam;
  int schedpolicy;
  /* Various flags like detachstate, scope, etc.  */
  int flags;
  /* Size of guard area.  */
  size_t guardsize;
  /* Stack handling.  */
  void *stackaddr;
  size_t stacksize;
  /* Affinity map.  */
  cpu_set_t *cpuset;
  size_t cpusetsize;
};
//\glibc-2.24\sysdeps\i386\nptl\tls.h
/* Return the thread descriptor for the current thread.

   The contained asm must *not* be marked volatile since otherwise
   assignments like
    pthread_descr self = thread_self();
   do not get optimized away.  */
# define THREAD_SELF   ({ struct pthread *__self;                                   asm ("movl %%gs:%c1,%0" : "=r" (__self)                            : "i" (offsetof (struct pthread, header.self)));                   __self;})

获取当前线程的结构体。

从父进程copy:

/* Set the stack guard field in TCB head.  */
#define THREAD_SET_STACK_GUARD(value) \
  THREAD_SETMEM (THREAD_SELF, header.stack_guard, value)
#define THREAD_COPY_STACK_GUARD(descr) \
  ((descr)->header.stack_guard                                 = THREAD_GETMEM (THREAD_SELF, header.stack_guard))


/* Set the pointer guard field in the TCB head.  */
#define THREAD_SET_POINTER_GUARD(value) \
  THREAD_SETMEM (THREAD_SELF, header.pointer_guard, value)
#define THREAD_COPY_POINTER_GUARD(descr) \
  ((descr)->header.pointer_guard                             = THREAD_GETMEM (THREAD_SELF, header.pointer_guard))

调用栈:

int __pthread_create_2_1 
(pthread_t *newthread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg)
    ==>retval = create_thread 
    (pd, iattr, true, STACK_VARIABLES_ARGS,&thread_ran);
        ==>static int create_thread 
        (struct pthread *pd, const struct pthread_attr *attr,bool stopped_start, STACK_VARIABLES_PARMS, bool *thread_ran)
            ==>  if (__glibc_unlikely (ARCH_CLONE (&start_thread, STACK_VARIABLES_ARGS,clone_flags, pd, &pd->tid, tp, &pd->tid)
                ==> __clone

然后看\glibc-2.24\sysdeps\unix\sysv\linux\x86_64\clone.S

/* The userland implementation is:
   int clone (int (*fn)(void *arg), void *child_stack, int flags, void *arg),
   the kernel entry is:
   int clone (long flags, void *child_stack).

   The parameters are passed in register and on the stack from userland:
   rdi: fn
   rsi: child_stack
   rdx:    flags
   rcx: arg
   r8d:    TID field in parent
   r9d: thread pointer
%esp+8:    TID field in child

   The kernel expects:
   rax: system call number
   rdi: flags
   rsi: child_stack
   rdx: TID field in parent
   r10: TID field in child
   r8:    thread pointer  */


        .text
ENTRY (__clone)
    /* Sanity check arguments.  */
    movq    $-EINVAL,%rax
    testq    %rdi,%rdi        /* no NULL function pointers */
    jz    SYSCALL_ERROR_LABEL
    testq    %rsi,%rsi        /* no NULL stack pointers */
    jz    SYSCALL_ERROR_LABEL

    /* Insert the argument onto the new stack.  */
    subq    $16,%rsi
    movq    %rcx,8(%rsi)

    /* Save the function pointer.  It will be popped off in the
       child in the ebx frobbing below.  */
    movq    %rdi,0(%rsi)

    /* Do the system call.  */
    movq    %rdx, %rdi
    movq    %r8, %rdx
    movq    %r9, %r8
    mov    8(%rsp), %R10_LP
    movl    $SYS_ify(clone),%eax

    /* End FDE now, because in the child the unwind info will be
       wrong.  */
    cfi_endproc;
    syscall

    testq    %rax,%rax
    jl    SYSCALL_ERROR_LABEL
    jz    L(thread_start)

    ret

L(thread_start):
    cfi_startproc;
    /* Clearing frame pointer is insufficient, use CFI.  */
    cfi_undefined (rip);
    /* Clear the frame pointer.  The ABI suggests this be done, to mark
       the outermost frame obviously.  */
    xorl    %ebp, %ebp

    andq    $CLONE_VM, %rdi
    jne    1f
    movl    $SYS_ify(getpid), %eax
    syscall
    movl    %eax, %fs:PID
    movl    %eax, %fs:TID
1:

    /* Set up arguments for the function call.  */
    popq    %rax        /* Function to call.  */
    popq    %rdi        /* Argument.  */
    call    *%rax
    /* Call exit with return value from function call. */
    movq    %rax, %rdi
    call    HIDDEN_JUMPTARGET (_exit)
    cfi_endproc;

    cfi_startproc;
PSEUDO_END (__clone)

libc_hidden_def (__clone)
weak_alias (__clone, clone)

看看syscall

//\glibc-2.24\sysdeps\unix\sysv\linux\x86_64\syscall.S                    
#include <sysdep.h>

/* Please consult the file sysdeps/unix/sysv/linux/x86-64/sysdep.h for
   more information about the value -4095 used below.  */

/* Usage: long syscall (syscall_number, arg1, arg2, arg3, arg4, arg5, arg6)
   We need to do some arg shifting, the syscall_number will be in
   rax.  */


    .text
ENTRY (syscall)
    movq %rdi, %rax        /* Syscall number -> rax.  */
    movq %rsi, %rdi        /* shift arg1 - arg5.  */
    movq %rdx, %rsi
    movq %rcx, %rdx
    movq %r8, %r10
    movq %r9, %r8
    movq 8(%rsp),%r9    /* arg6 is on the stack.  */
    syscall            /* Do the system call.  */
    cmpq $-4095, %rax    /* Check %rax for error.  */
    jae SYSCALL_ERROR_LABEL    /* Jump to error handler if error.  */
    ret            /* Return to caller.  */

PSEUDO_END 

 

pthread_create