Part 3 of 6 · 3 min read
Shared and private
| Item | Shared by all threads of a process? |
|---|---|
| Program code (text) | Yes |
| Global and static variables (data, BSS) | Yes |
Heap (memory from malloc) |
Yes |
| Open files and file descriptors | Yes |
| Process ID and parent | Yes |
| Stack (local variables, function calls) | No, one per thread |
| Registers and program counter | No, one set per thread |
| Thread ID | No, one per thread |
errno |
No, one per thread (page 4) |
In plain words: The program below prints the process ID, a thread ID, the address of a global variable and the address of a local variable in the main thread and in two other threads. The call gettid, a Linux-specific system call, returns the thread ID, which is a number the kernel gives each thread.
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <pthread.h>
int shared = 5;
static void *show(void *name) {
int local = 0;
printf("%-7s pid %d tid %ld &shared %p &local %p\n", (char *)name,
(int)getpid(), (long)syscall(SYS_gettid), (void *)&shared, (void *)&local);
return NULL;
}
int main(void) {
pthread_t a, b;
show("main");
pthread_create(&a, NULL, show, "thread1"); pthread_join(a, NULL);
pthread_create(&b, NULL, show, "thread2"); pthread_join(b, NULL);
return 0;
}
Output on the test machine:
main pid 30175 tid 30175 &shared 0x5569529f2010 &local 0x7ffe04495e64
thread1 pid 30175 tid 30176 &shared 0x5569529f2010 &local 0x7f5fef5feea4
thread2 pid 30175 tid 30177 &shared 0x5569529f2010 &local 0x7f5fef5feea4
Read it column by column. The process ID is the same, 30175, for all three. The thread IDs differ, and the first thread's ID equals the process ID: the main thread is the thread whose ID is the process ID. The address of shared is identical, which means all three see the same variable. The address of local is different in the main thread, which has the original stack, and in the other two. The two new threads show the same stack address only because the second thread was created after the first one had been joined, so the system reused the freed stack space.
The command ps and the file /proc/PID/status reflect this too. A program that starts 3 threads and then reads its own status file printed Threads: 4: the main thread plus 3 more.
Thread ID
A thread ID (TID) is the number the kernel assigns to each thread, which names that thread in the kernel's tables. On Linux the first thread of a process has a TID equal to the process ID.
Example: in the output above, the process has ID 30175 and its two extra threads have IDs 30176 and 30177 while they run.
Check yourself:
1. Why do all threads print the same address for shared?
2. Why does the main thread print a different local address from the others?
3. What does Threads: 4 in /proc/self/status count?