When working on Linux what happens when a thread is created? It is a separate execution flow. Does each thread have their own code section? Personally I don't think threads would be able to share code section even if it's the same section. Say if the number of threads being created is dynamic. How is the memory allocated for each thread? Will the memory foot print, especially code section, increase as threads are created?
1 Answers
(Although you asked about Linux, which would be off-topic, the same principles apply on most operating systems, and general principles are on-topic here.)
Threads share their code section. In many systems, even separate tasks that are executing the same program can share their code section, because the code sections are read-only, so whatever one task does won't affect the other task. I don't know how to explain this better because you don't say why you don't think it would be possible. It is possible, and it's routinely done.
Each thread has its own set of register values, including the program counter. Each thread also has its own call stack. Having its own program counter and call stack (in a way, the program counter is the top of the call stack) pretty much defines a thread. Multiple threads of the same task have program counters that each point at some place in the shared code section.
Creating a thread requires allocating memory to store its stack, and to store its register values when switching between threads. It doesn't affect the code section.
- 44,159
- 8
- 120
- 184