Process :
an instance of a running(or suspended) program
코드의 한 지점(한 thread)만 실행
A single process may have multiple threads of execution
light-weight processes that share access to a single memory space.global한 data, files descriptor는 모든 thread 간의 공유가 되고 있음. (하나의 process에서 여러 thread가 생성된 것)
하지만 각각의 thread들은 각각의 register, stack segment가 있음.

Kernel 영역은 똑같고, User 영역이 다름.
multi-thread process의 경우, 하나의 address space 안에서 Stack 영역에 각각의 thread별로 따로따로 존재한다.
각기 다른 function들을 호출해가기 때문.

process를 안 쓰는 이유 :thread를 사용하는 이유 :
Creating and Destroying Threads :

Using Pthreads :
gcc -o <threaded_program.c> -pthread : "pthread library와 link하여 compile하라"
pthread_create(3) : Create a new thread of control


void* (*start_routine)(void*) :error codes :
pthread_t type :pthread_self(3), pthread_equal(3) :
pthread_exit(3) : Thread termination4가지 방법
The thread function performs return with a return value :
The thread calls pthread_exit() with a return value :

Any of the threads calls exit() or the main thread performs a return :The thread is canceled using pthread_cancel(3) :
pthread_join(3) : waiting for threads
만약 여러 thread를 기다리려면 각각의 thread에 대해서 join해줘야 한다.
pthread_detach(3) :
명시된 thread가 종료되었을 때, 그 thread는 join하는 thread 없이 바로 갖고 있는 resource들을 release.
누군가가 pthread_join(3)하며 기다려줄 필요가 없는 경우.









-O2라는 2-level optimization option을 주었더니,
왜 그럴까?


아래 예시에서는 이론대로라면, 4개 Threads를 이용한게 single thread보다 약 4배 빨라야 하지만 실제로는 훨씬 느리다.
그 이유는 아래 예시와 같이, mutex lock을 매 반복마다 호출하면 엄청나게 느려진다.
mutex는 kernel level에서 scheduling이 들어가기 때문에 엄청나게 느려진다.
single thread about 11.11s
4 trheads about 55.9s
위 문제를 해결하기 위해, 각 thread에서는 global variable인 sum에 직접 값을 더하는게 아니라,
local variable에 값을 누적해서 최종적으로 global variable sum에 더해주는 딱 한 순간만 mutex를 호출하면 된다.
single thread about 1.29s
4 threads about 0.38s