From da62f6025f2984b8bc902e2515306a83c3d7d616 Mon Sep 17 00:00:00 2001 From: Fabio Scotto di Santolo Date: Mon, 28 Jul 2025 16:06:28 +0200 Subject: [PATCH] Added example chapter 7 on Threads --- README.md | 1 + chp7/README.md | 130 +++++++++++++++++++++++++++++++++++++++++++++++++ chp7/thread.c | 30 ++++++++++++ 3 files changed, 161 insertions(+) create mode 100644 chp7/README.md create mode 100644 chp7/thread.c diff --git a/README.md b/README.md index 8167389..40b4968 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ Welcome! This is a collection of chapter summaries from the book **Linux System - [Chapter 4 โ€“ Advanced File I/O](chp4/README.md) - [Chapter 5 - Process Management](chp5/README.md) - [Chapter 6 - Advanced Process Management](chp6/README.md) +- [Chapter 7 - Threading](chp7/README.md) - [Exercises](exercises/README.md) > Each file contains an English summary of the chapter's key concepts. diff --git a/chp7/README.md b/chp7/README.md new file mode 100644 index 0000000..04619cf --- /dev/null +++ b/chp7/README.md @@ -0,0 +1,130 @@ +# ๐Ÿงต Chapter 7: Threads โ€“ Summary + +## ๐Ÿ“Œ Key Concepts + +### ๐Ÿ”น What is a Thread? +- A thread is a **lightweight process** that shares the same address space (memory) with other threads of the same process. +- Threads allow concurrent execution within a single process, enabling **parallelism** and **responsiveness**. + +### ๐Ÿ”น Benefits of Threads +- More efficient than processes in terms of resource usage and context switching. +- Ideal for applications that perform blocking operations (e.g., I/O-bound tasks). +- Useful for **multicore scalability**. + +--- + +## ๐Ÿ› ๏ธ POSIX Threads API (pthreads) + +### โž• Creating Threads + +```c +int pthread_create(pthread_t *thread, const pthread_attr_t *attr, + void *(*start_routine)(void *), void *arg); +```` + +* Spawns a new thread running `start_routine(arg)`. +* Returns a `pthread_t` handle. + +### ๐Ÿ›‘ Joining Threads + +```c +int pthread_join(pthread_t thread, void **retval); +``` + +* Waits for the specified thread to terminate. +* Returns its return value if `retval` is not `NULL`. + +### โŒ Detaching Threads + +```c +int pthread_detach(pthread_t thread); +``` + +* Allows a thread to run independently. +* Its resources are automatically reclaimed on exit (cannot be joined). + +--- + +## ๐Ÿงฉ Thread Functions + +### Returning from a Thread + +* Use `return` or `pthread_exit()` to terminate a thread and optionally pass back a result. + +### Thread IDs + +* Use `pthread_self()` to get the calling thread's ID. + +--- + +## ๐Ÿ”’ Synchronization + +### Mutexes + +```c +pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; + +pthread_mutex_lock(&lock); +/* critical section */ +pthread_mutex_unlock(&lock); +``` + +* Used to prevent **data races** in shared memory. +* Must be used carefully to avoid **deadlocks**. + +### Condition Variables + +```c +pthread_cond_t cond = PTHREAD_COND_INITIALIZER; + +pthread_cond_wait(&cond, &mutex); +pthread_cond_signal(&cond); +``` + +* Used for thread coordination, e.g., waiting for a condition to become true. +* Must be used with an associated mutex. + +--- + +## ๐Ÿšง Common Pitfalls + +* Forgetting to initialize/destroy mutexes or condition variables. +* Accessing shared data without synchronization. +* Deadlocks from improper mutex locking order. +* Detached threads cannot be joined. +* Stack size: default per-thread stack may be small (configurable). + +--- + +## ๐Ÿงช Thread Safety + +* Not all C library functions are thread-safe (e.g., `strtok` is not, `strtok_r` is). +* Thread-local storage (TLS) can help isolate data per thread. + +--- + +## ๐Ÿ“‹ Summary Table + +| Function | Purpose | +| ----------------- | --------------------------------- | +| `pthread_create` | Create a thread | +| `pthread_join` | Wait for a thread to finish | +| `pthread_exit` | End a thread | +| `pthread_detach` | Run thread without joinable state | +| `pthread_mutex_*` | Locking primitives | +| `pthread_cond_*` | Waiting/signaling conditions | + +--- + +## โœ… Best Practices + +* Always check return values of pthread functions. +* Protect all shared data with mutexes or atomic operations. +* Use condition variables for coordination (not busy waiting). +* Prefer modular, short-lived threads when possible. +* Clean up thread resources (`pthread_join`, `pthread_detach`). + +--- + +*Last updated: 2025-07-28* + diff --git a/chp7/thread.c b/chp7/thread.c new file mode 100644 index 0000000..46c55fd --- /dev/null +++ b/chp7/thread.c @@ -0,0 +1,30 @@ +#include +#include +#include + +void *start_thread(void *message) +{ + printf("%s\n", (const char *)message); + return message; +} + +int main(void) +{ + pthread_t thing1, thing2; + const char *message1 = "Thing 1"; + const char *message2 = "Thing 2"; + + /* Create two threads, each with a different message. */ + pthread_create(&thing1, NULL, start_thread, (void *)message1); + pthread_create(&thing2, NULL, start_thread, (void *)message2); + + /* + * Wait for the threads to exit. If we didn't join here, + * we'd risk terminating this main thread before the + * other two threads finished. + */ + pthread_join(thing1, NULL); + pthread_join(thing2, NULL); + + return EXIT_SUCCESS; +}