Process | Thread |
---|---|
Context duplication | No need |
Difficult IPC | No need |
Protection (isolation) | If one thread crashes, all threads stop |
Simpler concurrency enforcement | Race conditions prone |
Slow (context switching) | Fast |
Traditionally processes have a single thread of control. (One instruction at any one time.)
Adding more threads of control to the same process allows multiple independent parts of the program to happen at the same time. Different threads spawned have different PCs.
Since all threads are shared within 1 process, they share:
On context switching:
Pros (process vs thread): Thus thread has more
Cons (process vs thread): But problems with
Process behaviour with threads (Implementation dependent):
fork
ing a 2-thread process give you a 2-threaded child? (Unix: no, 1 thread in child.)exit
: does it end all threads? (Unix: yes.)exec
: does it end all other threads other than the one called? (Unix: yes.)Handled by runtime system and implemented as a user library, not informed to kernel at all.
Thread is implemented in OS and handled via system calls. Scheduling on thread level possible, use threads for its own execution.
OS will schedule on the kernel threads whereas user threads bind to some kernel thread(s).
e.g. Simultaneous multi-threading (SMT/Hyperthreading) that supplies multiple sets of GPRs + special registers allowing threads to run natively and in parallel on the same core.
pthread
Standard definition of API and behaviour of threads. However the implementation isn’t specified by POSIX. So either user or kernel thread possible.
-lpthread
flag in gcc
call and #include <pthread.h>
necessarypthread_t
is the datatype of a thread id.pthread_attr_t
is the datatype of thread attributes.int pthread_create(
pthread_t *tid_created,
const pthread_attr_t *thread_attrs,
void* (*callFunction) (void*)
void *arg_for_startroutine
);
int pthread_exit(void *exitValue); // for syncing
// if pthread_exit isn't used,
// NO WAY to return an exit value and thread terminates
// once startroutine is done.
pthread_join()
(block until this other thread is complete.)int pthread_join(pthread_t tid, void **status)
// returns 0 if succeed, !0 if error.
// status == exit value, tid is the pthread to wait for