← Back to Home

CITS2002 - Lecture 19
Introduction to Multi-Threaded Programming - Slides

Introduction to Multithreading

  • Modern computers appear to run many tasks at once
  • The OS manages CPU scheduling and memory allocation to share limited resources among processes
  • Concurrency → multiple tasks progress at the same time

Threads

A thread is a lightweight unit of execution within a process

  • Each thread has:
    • Its own sequence of instructions and local variables
    • Access to shared global variables and resources
  • Threads allow:
    1. Handling asynchronous events more easily
    2. Parallel performance on multicore systems

Threads vs Processes

Memory & Resources:

  • Thread → shares memory and resources with other threads of same process
  • Process → has its own memory and resources

Creation Overhead:

  • Thread → creating and switching is faster
  • Process → creating and switching slow from separate memory management

Similarities:

  1. Both are individual units of execution that can be scheduled by CPU
  2. Both have their own program counter, registers and stack

Multithreading allows a single process to perform multiple tasks concurrently

  • Improves responsiveness and efficiency
    e.g. a UI remains active during I/O
  • Allows resource sharing
  • Allows scalability on multicore systems
    • One thread can only run on one core; split program into multiple threads on different cores

Unlike processes, which are independent and communicate via inter-process mechanisms, threads are lightweight and communicate through shared variables. Creating and switching threads is faster than creating new processes.

In C, threads are implemented using the POSIX threads (pthreads) library

  • pthread_create() – create new thread to run a specified function
  • pthread_exit() – terminates the calling thread
  • pthread_join() – waits for a specific thread to finish
    • Similar to wait() for processes
  • pthread_attr_t – specify attributes (e.g. detach state or stack size)

Threads can be joined (the creator waits for completion) or detached (they run independently and free their resources automatically). Each thread’s stack size can be adjusted using the pthread_attr_* functions when large local variables or recursion are used.


End of Unit!