mmap() 和 pthreads - 复制 VMA

mmap() and pthreads - copy VMA

mmap()一个匿名VMA。 pthreads 如何处理该 VMA? 我希望为每个线程复制 vma 及其内存。为此我需要哪些标志?

I mmap() an anonymous VMA. How do pthreads handle that VMA?

"pthreads"(Linux 中线程的 user-space 库)对来自 mmap 的新 VMA 没有特殊处理。

I want that the vma with its memory is copied for every thread.

你不能,因为单个进程的每个线程都有相同的 VMA。

glibc 中的默认 pthread 实现 - NPTL,使用带有 CLONE_VM 标志的 clone 系统调用: 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.

因此, 一个线程使用 mmap(2) 或 munmap(2) 执行的任何内存映射或取消映射都会被 linux glibc 中进程的所有线程看到线程。 mmap 不需要额外的标志; CLONE_VM flag 已经给了克隆。