Last active
December 24, 2015 21:39
-
-
Save caigen/6866941 to your computer and use it in GitHub Desktop.
pthread的底层实现
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 在linux内核源码中,文件include/linux/sched.h说: | |
| /** | |
| * cloning flags: | |
| */ | |
| #define CSIGNAL 0x000000ff /** signal mask to be sent at exit */ | |
| #define CLONE_VM 0x00000100 /** set if VM shared between processes */ | |
| #define CLONE_FS 0x00000200 /** set if fs info shared between processes */ | |
| #define CLONE_FILES 0x00000400 /** set if open files shared between processes */ | |
| // 在glibc中,文件nptl/sysdeps/pthread/createthread.c说: | |
| static int | |
| create_thread (struct pthread *pd, const struct pthread_attr *attr, | |
| STACK_VARIABLES_PARMS) | |
| { | |
| #ifdef TLS_TCB_AT_TP | |
| assert (pd->header.tcb != NULL); | |
| #endif | |
| /** We rely heavily on various flags the CLONE function understands: | |
| CLONE_VM, CLONE_FS, CLONE_FILES | |
| These flags select semantics with shared address space and | |
| file descriptors according to what POSIX requires. | |
| CLONE_SIGNAL | |
| This flag selects the POSIX signal semantics. | |
| CLONE_SETTLS | |
| The sixth parameter to CLONE determines the TLS area for the | |
| new thread. | |
| CLONE_PARENT_SETTID | |
| The kernels writes the thread ID of the newly created thread | |
| into the location pointed to by the fifth parameters to CLONE. | |
| Note that it would be semantically equivalent to use | |
| CLONE_CHILD_SETTID but it is be more expensive in the kernel. | |
| CLONE_CHILD_CLEARTID | |
| The kernels clears the thread ID of a thread that has called | |
| sys_exit() in the location pointed to by the seventh parameter | |
| to CLONE. | |
| CLONE_DETACHED | |
| No signal is generated if the thread exists and it is | |
| automatically reaped. | |
| The termination signal is chosen to be zero which means no signal | |
| is sent. */ | |
| int clone_flags = (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGNAL | |
| | CLONE_SETTLS | CLONE_PARENT_SETTID | |
| | CLONE_CHILD_CLEARTID | CLONE_SYSVSEM | |
| #if __ASSUME_NO_CLONE_DETACHED == 0 | |
| | CLONE_DETACHED | |
| #endif | |
| | 0); | |
| // 于是:线程与其父进程共享VM、FS、FILES等。这也是线程与进程的区别点。通常Fork出来进程(复制资源),Clone出来线程(共享资源)。Fork调用无参数,Clone调用传参控制。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment