Chapter 4: Multithreaded Programming
Created: 2025-12-16
Updated: 2025-12-16
Pthread := the implementation of POSIX Threads POSIX := Portable Operating System Interface for Unix, same API but can have different syscall implementations
pthread_create(*thread, attr, routine, &arg)
// thread: pointer to thread ID
// attr: thread attributes (NULL for default)
// routine: function to be executed by the thread
// arg: argument to the function
pthread_join(thread, *retval) // blocking
// thread: thread ID to wait for
// retval: pointer to return value (NULL if not needed)
pthread_detach(thread)
// thread: thread ID to detach
pthread_exit(*retval)
// retval: return value to be collected by pthread_join
clone() syscall: create a new process and a link pointing to the associated data of the parent process
clone = fork)CLONE_VM: share memory spaceCLONE_FS: share file system infoCLONE_FILES: share file descriptorsCLONE_SIGHAND: share signal handlerspthread_kill())// example
void *PrintHello(void *threadid) {
long tid = (long)threadid;
printf("Hello World! Thread ID, %ld\n", tid);
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
for (long tid=0; tid<NUM_THREADS; ++tid) {
pthread_create(&threads[tid], NULL, PrintHello, (void*)tid);
// when passing only a single value, can cast directly to (void*)
// otherwise, we can define a struct to hold, and pass its pointer
}
pthread_exit(NULL); // main() exit but process still alive
// not recommended, usually do `pthread_join` and return 0
}