5 – Threads

Summary

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

Why Thread

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:

Process and Thread

On context switching:

Pros (process vs thread): Thus thread has more

Cons (process vs thread): But problems with

Process behaviour with threads (Implementation dependent):

Types of thread

User thread

Handled by runtime system and implemented as a user library, not informed to kernel at all.

Kernel thread

Thread is implemented in OS and handled via system calls. Scheduling on thread level possible, use threads for its own execution.

Hybrid thread

Hybrid threading

OS will schedule on the kernel threads whereas user threads bind to some kernel thread(s).

Modern threading

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.

POSIX threads pthread

Standard definition of API and behaviour of threads. However the implementation isn’t specified by POSIX. So either user or kernel thread possible.

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.
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