1. Home
  2. Explore
  3. Computer Science
  4. Parallel Computing

Study methods

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

Parallel Computing

Parallelization, Processes, and Threads

Parallelization in computer systems

Parallelization divides a large job into smaller tasks that can be performed at the same time by multiple computing entities. When the tasks run concurrently on different processors or cores, the overall job can finish sooner than if one processor completes it sequentially.

A simple example is a job that takes one person 10 days: if the work can be divided evenly and 10 people can work independently, each person can complete one-tenth of the job, allowing the whole job to finish in about one day. Computer systems use the same general idea: divide work, assign portions to separate execution entities, and combine the partial results.

  • Task division: A large problem is split into smaller parts.

  • Concurrent execution: The parts run at the same time when hardware resources permit.

  • Result combination: Partial results are combined to produce the final answer.

Modern hardware includes graphics processing units (GPUs), which can perform thousands of relatively small tasks in parallel. This is useful when a large workload consists of many independent operations.

Parallelization does not automatically guarantee a particular speedup. The workload must be divisible, the tasks must have enough independence, and the system must have enough processing resources. Work that is inherently sequential or coordination overhead can limit the benefit.


Sequential and parallel summation

Consider a program that calculates a sum by iterating through a large range of integers. In a sequential version, one execution entity performs the entire loop. Even if the computer has several processors, that particular program may use only one processor at a time, leaving other processors available for other work or idle.

For a workload of 10 million numbers and four processors, the range can be divided into four portions of 2.5 million numbers each:

  • The first portion covers the beginning of the range.

  • The second portion covers the next 2.5 million numbers.

  • The third portion covers the next 2.5 million numbers.

  • The fourth portion covers the final 2.5 million numbers.

Each execution entity calculates a partial sum for its assigned portion. The partial sums are then added together to obtain the overall result. If the portions are balanced and can run simultaneously, the computation can take substantially less time than a single sequential loop.

The ranges must be assigned so that they are disjoint and together cover the intended input exactly. This avoids both omitting values and counting values more than once.


Using processes for parallel work

A process is an executing program with its own address space and other resources. One approach to parallelization is to create several processes, each of which performs one part of the work. In the four-way summation example, four processes could each calculate one quarter of the total.

A process is commonly created in Unix-like systems using the fork system call. Each child process can then execute its assigned portion of the computation.

Process isolation and communication

Processes are isolated from one another. Each process has its own execution environment, including its own:

  • Instructions, or code

  • Data and global variables

  • Heap

  • Stack

  • Memory map

Because one process generally cannot directly access another process’s private memory, processes need inter-process communication (IPC) to exchange information or results.

Common IPC approaches include:

  • Message passing: Processes use mechanisms such as send and receive operations. The operating system provides a channel for exchanging messages.

  • Shared memory: The operating system helps create a memory region that multiple processes can access. Processes use that common region to exchange data.

Process creation, termination, and many resource-management operations involve operating-system services, typically accessed through system calls.

Costs of process-based parallelization

Process-based parallelism can have significant overhead:

  • Process-management overhead: Creating and managing multiple processes requires operating-system work.

  • System-call overhead: A system call transfers control to the operating system, which identifies the requested operation and runs the appropriate handler.

  • Communication overhead: Isolated processes need IPC to exchange data or combine results.

  • Resource duplication: Multiple processes may contain copies of similar code and data.

Processes are useful when strong isolation is important, but their separation can make fine-grained parallel work more expensive to coordinate.


Threads: lightweight execution entities

A thread is an execution entity within a process. Threads are often described as lightweight processes because they provide separate execution paths while sharing much of the process’s resources.

Instead of creating four separate processes for the summation task, a program can create one process containing four threads. Each thread calculates one partial sum. If the system has enough processing resources, the threads can run in parallel.

What threads share

Threads in the same process share the process’s:

  • Code

  • Global data

  • Heap

  • Open files and other process resources

Sharing makes communication between threads straightforward: one thread can place data in shared global memory or the heap, and another thread in the same process can access it.

What each thread has separately

Each thread has its own:

  • Stack, used for local variables and function-call information

  • Execution context, including the register values needed to resume execution

For example, a thread’s instruction pointer identifies where it is executing, and its stack pointer identifies the current location in its stack. When a thread is paused and later resumed, its execution context allows it to continue from the appropriate point.

Threads in one process may run simultaneously on separate processors or may take turns on the same processor. The operating system schedules them onto available processing resources.


Why threads can be more efficient than processes

Threads reduce some of the costs associated with creating parallel work.

Lower creation and management cost

Creating a thread is generally less expensive than creating a process because threads share the process’s address space and resources rather than requiring an entirely separate process environment. A comparison described in the source illustrates this difference: on one machine, creating 50,000 processes took 8.1 time units, while creating 50,000 threads took 0.9 time units. The exact times depend on the machine and system, but the comparison demonstrates that thread creation can be substantially more efficient.

Thread-management operations may be handled through a threading library and do not necessarily require the same system-call work as process-management operations.

Easier communication

Threads in a process can communicate through shared global data or shared heap memory. In contrast, isolated processes typically need IPC mechanisms, such as message passing or shared memory, to exchange information.

Shared access is convenient, but it also means that threads must coordinate carefully when they access data that multiple threads may change. In the summation example, each thread can write its own partial result into a separate array element, reducing the chance of conflicting writes.

Faster context switching

Switching between threads in the same process can be faster than switching between processes because:

  • A thread’s execution context is smaller than the complete state associated with a process.

  • Threads in the same process use the same address space and page tables, so a switch between them does not normally require changing to a different process’s page tables.

  • Translation lookaside buffer (TLB) entries may remain useful because the address space has not changed.

A process switch can require more work to save and restore state and to change memory-management context.


Processes compared with threads

Process

  • A process is an independent execution entity with its own address space.

  • It has its own code, data, heap, stack, and other process state.

  • It can execute with a single thread and remain a complete process.

  • Processes are isolated, so communication between them generally uses IPC.

Thread

  • A thread is an execution path within a process and cannot execute independently of a process.

  • Threads in one process share code, global data, heap memory, and open files.

  • Each thread has its own stack and execution context.

  • A thread can terminate while the rest of the process continues.

  • If the process terminates, all of its threads terminate as well.

For instance, if a process has 10 threads and one exits, the other nine may continue executing. If the process itself ends, none of its threads can continue.


Creating and managing threads with pthreads

One widely used threading library in C programs is pthreads. Its functions provide ways to create threads, end them, and wait for them.

Creating a thread

The pthreads creation function, pthread_create, takes four main arguments:

  1. Thread identifier: A pointer to storage where the new thread’s identifier, or TID, is placed. This identifies the thread, much as a process ID identifies a process.

  2. Thread attributes: Optional settings that describe properties of the new thread. A null value requests default attributes.

  3. Start routine: A pointer to the function that the new thread begins executing.

  4. Argument: A value passed to the start routine, commonly used to tell the thread which portion of the work to perform.

Calling this function creates a new thread context within the process. The thread begins execution at the specified start routine.

Ending a thread

A thread can end by returning from its start routine or by calling pthread_exit. The function can provide a return status that another thread may later retrieve.

Waiting for a thread

The pthread_join function makes one thread wait for a particular other thread to finish. The caller supplies the identifier of the thread to wait for. The call blocks until that thread exits, and the caller can then obtain the thread’s exit status.

This is important when a program needs all partial computations to finish before combining their results.


Applying pthreads to the summation task

A multithreaded version of the summation program can use four threads:

  1. The main thread declares four thread identifiers.

  2. It invokes the creation function four times, passing a different identifier location and work assignment for each thread.

  3. Each new thread starts at the same worker function but receives a different argument identifying its portion of the input.

  4. The worker function calculates the partial sum for its assigned range.

  5. Each thread stores its result in a different element of a shared global array.

  6. The main thread invokes a join operation for each thread, waiting until all four have finished.

  7. After all joins complete, the main thread adds the four partial sums and prints the final result.

For example, a thread argument might identify one of four portions using an index in the range 000 through 333. The worker function uses that index to determine the portion’s starting and ending values.

Because each thread writes to a separate result element, the threads do not need to update the same partial-sum location. This is a simple way to avoid conflicting writes in this example. More generally, shared data must be designed and coordinated carefully when multiple threads can access or modify it.

The program’s pthreads library must be linked when compiling. A typical Linux compilation command includes the option -lpthread.


Other threading libraries

Pthreads are not the only way to write multithreaded programs. Other threading libraries include:

  • Windows threads, used for Windows-based applications

  • Boost, a C++ library that includes threading support

  • Linux threads, a Linux threading implementation

The choice of library depends on the operating system, programming language, and application requirements. The fundamental idea remains the same: a process contains multiple execution contexts that can share process resources while performing separate parts of a task.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent