简体   繁体   English

Linux线程和进程

[英]Linux threads and processes

I have a simple question about Linux threads and processes. 我有一个关于Linux线程和进程的简单问题。

The process in Linux has a separate virtual address space which consists of Linux中的进程具有单独的虚拟地址空间,其中包括

- stack
- heap
- bss
- code/text
- data

A process can have 'n' threads inside them.I understand that they do share the address space of the process.However since the function calls that are executed by different threads can be different, does a thread have a separate stack segment.? 一个进程内部可以有n个线程,我知道它们确实共享进程的地址空间,但是由于不同线程执行的函数调用可以不同,所以一个线程有一个单独的堆栈段吗?

  1. Threads share the all the memory segments, including the stack segment. 线程共享所有的内存段,包括堆栈段。
  2. Each thread has a separate stack. 每个线程都有一个单独的堆栈。

Both are true. 两者都是对的。 I know they sounds like contradiction. 我知道他们听起来像矛盾。

The first thread's stack uses the so called "stack segment". 第一个线程的堆栈使用所谓的“堆栈段”。 It's allocated by the kernel. 它由内核分配。

# cat /proc/self/maps
...
7fffbe0b0000-7fffbe0d1000 rw-p 00000000 00:00 0                          [stack]
...

Threads created later (eg created by pthread_create() or clone(CLONE_VM)) use heap (or private anonymous mmap which is the same as heap in every ways) as their stack. 以后创建的线程(例如,由pthread_create()或clone(CLONE_VM)创建的)将堆(或在各个方面都与堆相同的私有匿名mmap)用作其堆栈。 It's allocated by the user program and passed to clone(). 它由用户程序分配,并传递给clone()。

In short, each thread uses a separate stack. 简而言之,每个线程使用单独的堆栈。 All the threads can read/write every other threads' stack. 所有线程都可以读取/写入其他所有线程的堆栈。

是的,在POSIX线程模型下,每个线程都有自己的堆栈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM