Multithreaded Programming - Operating System Concepts Chapter 4
ちょっとしたメモ。
Operating System Concepts の Chapter 4 の冒頭に
A thread is a basic unit of CPU utilization; it comprises a thread ID, a program counter, a register set, and a stack. It shares with other threads belonging to the same process its code section, data section, and other operating-system resources, such as open files and signals.
出典: https://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/4_Threads.html
と書かれている。
ざっくりいうと、プログラムカウンタ、レジスタ、スタックはそれぞれで保持するけど、データセクション(含 グローバル変数)、オープンファイルやシグナルは共有するということ。
グローバル変数について実際に確認してみる。
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <pthread.h> int x = 0; pthread_t tid[2]; void* incr() { x = x + 1; printf("%d\n", x); } int main() { int i = 0; int err; while(i < 10) { err = pthread_create(&(tid[i]), NULL, &incr, NULL); if (err != 0) printf("can't create thread\n"); i++; } sleep(1); }
$ gcc -pthread thread.c && ./a.out 1 2 3 4 5 6 7 8 9 10
確かに、スレッドで共有されていることが確認できる。
次に、fork(2)で同じようなコードを書いてみる。
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <pthread.h> int x = 0; void* incr() { x = x + 1; printf("%d\n", x); } int main() { int i = 0; int err; pid_t pid; while(i < 10) { pid = fork(); // child if (pid == 0) { incr(); exit(0); } // parent i++; } sleep(1); }
$ gcc fork.c && ./a.out 1 1 1 1 1 1 1 1 1 1
これは共有されない。