1. Home
  2. Explore
  3. Computer Science
  4. Concurrency in Operating Systems

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Concurrency in Operating Systems

Concurrency in UNIX Programs

Concurrency, parallelism, and why they matter

Concurrency is the ability to make progress on multiple activities during the same period of time. A program can be designed as separate, relatively independent lines of work so that the system can switch among them—or run them simultaneously—without their interfering incorrectly.

Concurrency is useful because a process may be unable to use the CPU while it waits for input or output. The operating system can let another process use the CPU during that wait, improving overall system efficiency and responsiveness.

Parallelism is the actual simultaneous execution of multiple activities, usually on separate CPU cores. Concurrency does not always mean that work runs at precisely the same instant: a single core can create the illusion of simultaneous activity by switching rapidly between tasks. A multicore processor can execute different tasks at the same time.

A concurrent program is easiest to reason about when its components can make progress independently. When they share data or resources, coordination is needed to prevent interference.


Processes, system calls, and library functions

A process is a running instance of a program. It has its own execution state and resources managed by the operating system. UNIX systems can run multiple processes, including multiple instances of the same program.

System calls

A system call is a request by a process for a service provided by the operating system’s kernel. The call transfers control from the program to the kernel. The process may be blocked while the kernel performs the requested operation; a blocked process cannot continue past the call until the operation completes.

Input/output operations such as reading from or writing to a file are common examples. The process requests work it cannot perform directly, and the operating system handles it.

Library functions

A C library function is a function supplied by a software library, such as a function for calculating a square root or formatting output. It runs as part of the program rather than necessarily transferring control to the kernel.

The distinction is about where the service is provided: system calls request kernel services, while library functions provide functionality through library code. Some library functions may themselves make system calls, and some operations can wait, so a library function is not guaranteed to be nonblocking.


How operating systems share CPU time

Multiprogramming

Multiprogramming means that multiple processes are available to run. When one process cannot proceed—for example, because it is waiting for an input/output operation—the operating system can run another process.

A context switch is the change from executing one process (or thread) to executing another. The operating system saves the state of the activity that is being paused and restores the state of the activity that is resuming.

In the basic multiprogramming model, a blocked process gives up the CPU while it waits. It becomes eligible to run again when its blocking operation completes.

Timesharing

Timesharing divides CPU time among multiple processes, often by giving each a short interval in which to run. The operating system switches between them frequently enough that users can experience several programs as active at once.

The key contrast is:

  • Multiprogramming: a process can give up the CPU when it cannot continue, such as while waiting for I/O.

  • Timesharing: the operating system also switches tasks to share CPU time, even when a process could otherwise continue running.

The scheduling policy determines when activities run and how CPU time is allocated. Processes may also communicate with one another, though communication requires mechanisms beyond simply sharing CPU time.

Multiprocessing

Multiprocessing means that multiple processes can execute at the same time on separate processing units. Modern CPUs often contain multiple cores, each capable of executing work independently. A core can itself switch among multiple activities, combining multiprocessing with multiprogramming and timesharing. Some processor technologies can expose additional logical execution units, allowing further concurrency.


Shared resources and race conditions

Concurrent processes or threads may share data or other resources. Sharing can be intentional, but it creates risks:

  • Security and privacy: one activity may gain access to data that should be restricted.

  • Resource contention: multiple activities may need the same resource at once.

  • Race conditions: the result depends unexpectedly on the relative timing of operations.

A race condition is a flaw in which the outcome of a system or process depends critically on the timing or ordering of events. It may appear only under a rare combination of circumstances, which can make it difficult to reproduce during testing.

Example: concurrent bank withdrawals

Suppose an account has 100. Two ATMs each attempt to withdraw 20. A withdrawal may consist of these steps:

  1. Read the account balance into memory.

  2. Subtract 20 from the in-memory value.

  3. Write the new balance back to the account.

If both withdrawals read 100 before either writes, each may calculate a new balance of 80. Both then write 80. The account has paid out 40 while recording only a 20 reduction, effectively allowing an extra 20 to be withdrawn.

The individual steps may each work correctly, but the combined operations are not protected from interleaving. The account update must be treated as a coordinated operation.

Why race conditions are difficult to detect

A race condition may require very specific timing—for example, two operations must overlap in a particular way. It may therefore occur rarely in ordinary use or testing. Small changes in system load, scheduling, or input speed can affect whether the flaw appears.

A well-known safety failure involved the Therac-25, a radiation therapy machine. Its design relied on software interlocks, and the system could be operated faster than its designers had anticipated. Under particular timing conditions, errors could be bypassed. The resulting failures caused deaths and serious injuries. The broader lesson is that safety-critical systems require carefully designed protections; timing-sensitive software behavior must not be assumed safe simply because it usually works.


Access control and locks

When multiple activities can update a shared resource, access must be coordinated. In particular, if one activity is writing to a resource, other activities should not read or write it until that update is complete when such access could lead to inconsistent results.

A lock is a mechanism that grants controlled access to a resource. An activity that acquires the lock may enter the protected region; other activities must wait or use another permitted approach until the lock is released. The protected region is the part of the program that accesses the shared resource.

Locking is a general idea implemented in different ways. Support may come from the operating system, hardware, or software libraries. Using a lock correctly is the programmer’s responsibility: the lock must protect the operations that actually need coordination, and it must be released when the protected work is complete.

Lock files

One simple approach between processes is to use a lock file. Processes agree on a known file path and attempt to create the lock file in a way that fails if it already exists. Successful creation indicates that the process acquired the lock; an existing file indicates that another process may already hold it.

A process that cannot acquire the lock can wait briefly and try again. If an unexpected error occurs, it should handle or report the failure rather than treating every failure as evidence that another process owns the lock.

The creation must be performed atomically: checking for a file and creating it as separate operations could itself allow two processes to believe they acquired the lock. Lock-file designs also need a way to handle abandoned files, such as after a process terminates unexpectedly.


The kernel and scheduler

The kernel is the central part of an operating system. It contains core operating-system routines and components that mediate access to hardware, including mechanisms that communicate with devices through drivers.

One of the kernel’s central responsibilities is scheduling. The scheduler decides which eligible process or thread runs on a CPU and for how long, according to the system’s scheduling policy. Programs ordinarily do not directly control the kernel; they request its services through system calls.


Threads: concurrent work within a process

A thread is an individual line of execution within a process. A process can contain multiple threads, each responsible for a different task. For example, a chat server might use distinct lines of work to accept user connections, receive messages, and distribute outgoing messages.

Threads allow a single program to organize several activities that would otherwise compete for attention within one execution path. The scheduler can switch among kernel-managed threads, and multiple threads may run simultaneously on different cores.

What threads share and what they have separately

Threads in the same process share many resources:

  • Program code: each thread can execute code belonging to the same program.

  • Heap memory: dynamically allocated memory is available to the process’s threads.

  • Global and static data: threads can access the process’s shared global variables and static variables.

Each thread has its own stack, which stores information such as function-call state, return locations, and automatic local variables. Although stacks are separate by convention, they reside in the process’s address space; code can access another thread’s stack if it has a valid address. Such access requires care because each thread’s local execution state may change independently.

Because threads share an address space and many resources, communication between threads can be simpler than communication between separate processes. However, shared memory also makes accidental interference and race conditions easier to create.

Switching between threads of the same process can be less expensive than switching between separate processes because the process’s shared address space does not need to be replaced. The scheduler can run kernel-level threads independently, including on different CPU cores.

Thread disadvantages

Threads introduce coordination and safety challenges:

  • Race conditions: concurrent access to shared data can produce incorrect results.

  • Resource contention: threads may compete for files, devices, or other resources. A system call involving a resource may block while that resource is unavailable.

  • Data exposure: shared address-space data may be accessible to any thread in the process. Sensitive information should not be assumed isolated merely because different parts of a program use different threads.


Kernel-level and user-level threads

Kernel-level threads

Kernel-level threads are managed by the operating system. The kernel knows about them and its scheduler assigns them CPU time. They can be scheduled independently, including on separate cores.

On UNIX-like systems, kernel-level threads can be created using standard thread libraries. They are the common choice for general-purpose multithreaded applications because the operating system can schedule them independently and because established APIs are available.

User-level threads

User-level threads are managed within a process by a user-space thread system. The kernel sees the process as a schedulable activity but does not manage each user-level thread individually. Switching between user-level threads can be fast because it can be performed within the process without asking the kernel to schedule a different kernel thread.

Their limitations include:

  • The scheduler may pre-empt the process as a whole, pausing all of its user-level threads.

  • A blocking system call by the process may block the entire process, rather than only the user-level thread that made the call.

  • They require additional management mechanisms and are less commonly used for ordinary UNIX application development.

User-level threads are sometimes called green threads. They can be useful in specialized designs, but kernel-level threads are generally more suitable for common applications.


POSIX threads

POSIX threads, commonly called Pthreads, are a standardized interface for creating and managing threads on UNIX-like systems. POSIX specifies common interfaces so that programs can use consistent thread operations across compatible systems.

A C program using Pthreads includes the pthread.h header. When compiling, the program must also be linked with the thread library using the appropriate compiler option, commonly -pthread with GCC.

Creating a thread with pthread_create

The Pthreads function pthread_create starts a new thread. Its four arguments serve these purposes:

  1. Thread ID output: a pointer to a variable where the new thread’s identifier is stored. A thread ID is an opaque identifier and should not be assumed to be a simple, human-readable integer.

  2. Attributes: a pointer to thread attributes, or a null pointer when default attributes are sufficient.

  3. Start routine: a function pointer naming the function at which the new thread begins execution.

  4. Argument: one pointer passed to the start routine. To pass multiple values, a program can place them in a structure and pass a pointer to that structure.

The start routine is a function, so its name is passed as a function pointer rather than called directly. The new thread begins executing that function after it is created. The return code from pthread_create should be checked to determine whether creation succeeded.

Passing arguments safely

A thread start routine commonly accepts a void * argument, allowing different kinds of data to be passed through a pointer. If the routine expects an integer stored elsewhere, it can convert the pointer to an integer pointer and dereference it.

When multiple threads are created in a loop, each thread must receive a stable, distinct argument value. Passing a pointer to a single loop variable can cause several threads to observe the same or changing value. A program can instead use a separate argument slot for each thread, as in an array of arguments, and ensure those values remain valid for the lifetime of the threads’ use.

A start routine can return a void *, providing a way to return a pointer-sized result. The receiving code must know what type of value that pointer represents and manage its lifetime appropriately.

Identifying a thread

A thread can obtain its own identifier with pthread_self. Thread identifiers can be compared using the Pthreads comparison mechanism, such as pthread_equal, rather than assuming they can be compared or printed as ordinary integers.

These functions allow a program to distinguish the currently executing thread from another thread whose ID it has stored.


Ending threads and waiting for completion

A thread can finish in several ways:

  • It can call pthread_exit to terminate itself.

  • It can return from its start routine, reaching the end of the function.

  • Another thread can request cancellation using pthread_cancel, subject to the cancellation behavior and state of the target thread.

  • If any thread calls exit, the entire process terminates, so all its threads end.

A thread that has completed does not necessarily mean that the rest of the program has waited for it or collected its result. The main thread can call pthread_join to wait for a particular joinable thread to finish. The calling thread blocks until the target thread terminates, then continues. Joining also provides a place to collect a thread’s return value when one is used.

If a program joins threads in a particular sequence, it waits in that sequence. For example, joining thread 0 before thread 1 means the main thread waits for thread 0 first, even if thread 1 finishes earlier. The order in which threads execute and print messages is generally determined by scheduling and is not guaranteed.

Typical multithreaded program flow

A basic program creating several worker threads generally follows this sequence:

  1. Define the worker function and decide what argument each thread needs.

  2. Allocate storage for thread IDs and for any per-thread arguments.

  3. Create each thread, checking the result of every creation.

  4. Continue with any work the main thread must perform.

  5. Join each thread that must be awaited, checking each result.

  6. Finish the program after the required threads have completed.

The output from the worker threads may appear in an unpredictable order because they run concurrently. A worker may start printing before the main thread has finished creating all the other workers.

Returning from main versus calling exit

A C main function is expected to return an integer status to the operating system. Returning from main is the normal way for a program to finish. Calling exit terminates the entire process immediately from that point and supplies an exit status; it is useful when termination is required from elsewhere in a program, but it is generally unnecessary at the end of main.


Mutexes and mutual exclusion

A mutex is a synchronization object whose name comes from mutual exclusion. It provides a lock that can protect shared data or a resource so that only one thread at a time enters the protected section.

A mutex does not automatically protect data. The program must explicitly lock it before accessing the shared resource and unlock it afterward. Every thread that accesses the protected resource must follow the same locking protocol.

Mutex life cycle and operations

A Pthreads mutex has a type such as pthread_mutex_t. A statically initialized mutex can use PTHREAD_MUTEX_INITIALIZER; a dynamically initialized mutex can be initialized with the relevant Pthreads function. When the mutex is no longer needed, it can be destroyed with pthread_mutex_destroy.

The standard locking sequence is:

  1. Call pthread_mutex_lock before accessing the shared resource.

  2. Perform the operations that must be protected.

  3. Call pthread_mutex_unlock when the protected work is complete.

If a thread attempts to lock a mutex that is already locked, it blocks until the mutex becomes available. The thread that holds the mutex is responsible for unlocking it. After it is unlocked, one of the waiting threads may acquire it; which waiting thread proceeds is not generally guaranteed by the mutex itself.

Pthreads also provides pthread_mutex_trylock, which attempts to acquire a mutex without waiting. The result indicates whether the lock was acquired or was already unavailable. This is useful when a thread needs to take a different action rather than block.

Locks must be used consistently. Failing to release a lock can leave other threads blocked indefinitely, while unlocking too early can expose shared data to conflicting updates.


Semaphores and their relationship to mutexes

A semaphore is a synchronization mechanism that represents availability of one or more resources. It can coordinate access to items such as buffers, open-file capacity, or connections.

Counting semaphores

A counting semaphore stores a count representing how many units of a resource are available. Acquiring a unit decreases availability; releasing it increases availability. This lets a program limit how many activities can use a resource at once.

Binary semaphores and mutexes

A binary semaphore has two states, often described as available and unavailable. A mutex behaves like a lock with these two states, but a mutex also has ownership semantics: the thread that locks it is responsible for unlocking it.

A mutex is therefore a specific mutual-exclusion mechanism, while “semaphore” refers to a broader family of synchronization tools. Semaphore concepts have been used in operating systems and concurrent programming since the early development of these ideas, and remain important in modern multicore programming.

When multiple threads or processes can update shared state, correctness depends on coordinating the entire operation—not merely protecting individual reads or writes.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent