我是一个匿名的VMA。pthreads如何处理VMA?
我希望每个线程都复制vma及其内存。为此我需要哪面旗帜?
最佳答案
一个匿名的VMA。pthreads如何处理VMA?
“pthreads”(Linux中线程的用户空间库)对mmap中的新VMA没有特殊处理。
我希望每个线程都复制vma及其内存。
不能,因为每个进程的线程都有相同的VMA。
glibc中的默认pthread实现-NPTL使用带有clone
标志的CLONE_VM
系统调用:
http://code.metager.de/source/xref/gnu/glibc/sysdeps/unix/sysv/linux/createthread.c
47 static int
48 create_thread (struct pthread *pd, const struct pthread_attr *attr,
49 bool stopped_start, STACK_VARIABLES_PARMS, bool *thread_ran)
50 {
66 /* We rely heavily on various flags the CLONE function understands:
67
68 CLONE_VM, CLONE_FS, CLONE_FILES
69 These flags select semantics with shared address space and
70 file descriptors according to what POSIX requires.
94 const int clone_flags = (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SYSVSEM
95 | CLONE_SIGHAND | CLONE_THREAD
96 | CLONE_SETTLS | CLONE_PARENT_SETTID
97 | CLONE_CHILD_CLEARTID
98 | 0);
99
102 if (__glibc_unlikely (ARCH_CLONE (&start_thread, STACK_VARIABLES_ARGS,
103 clone_flags, pd, &pd->tid, tp, &pd->tid)
man page of clone说:
CLONE_VM (since Linux 2.0)
If CLONE_VM is set, the calling process and the child process
run in the same memory space. In particular, memory writes
performed by the calling process or by the child process are
also visible in the other process. Moreover, any memory
mapping or unmapping performed with mmap(2) or munmap(2) by
the child or calling process also affects the other process.
因此,在linux glibc pthreads中,进程的所有线程都可以看到由一个线程使用mmap(2)或munmap(2)执行的任何内存映射或取消映射。不需要对mmap附加标志;CLONE_VM标志已被赋予CLONE。