Unix - difference between Multithreading and Multiprocessing in UNIX/Linux.

1. Definitions

Multiprocessing

  • Uses multiple processes.

  • Each process has its own memory space and resources.

  • Communication happens via IPC (pipes, sockets, shared memory, message queues).

Multithreading

  • Uses multiple threads within a single process.

  • Threads share memory and resources of the parent process.

  • Communication is easier and faster (since all threads can access shared data directly).


2. Key Differences

Feature Multiprocessing Multithreading
Definition Parallel execution of multiple processes Parallel execution of multiple threads inside one process
Memory Each process has separate memory space Threads share common memory (code, data, heap)
Communication Requires IPC (slower) Direct (faster, shared variables)
Creation Cost High (creating process with fork() is heavy) Low (creating thread with pthread_create() is lightweight)
Fault Isolation Safer – if one process crashes, others run fine Risky – if one thread crashes, it may affect whole process
Context Switching Slower (involves switching memory) Faster (same memory, just stack/registers)
CPU Usage Good for CPU-intensive tasks Good for I/O-bound and lightweight tasks
Example Web server spawning multiple processes Web server using worker threads per request

3. Examples in UNIX

Multiprocessing Example

# Run two processes in parallel
gedit &    # Process 1
firefox &  # Process 2

Each runs as a separate process with its own PID.

Multithreading Example (C with pthreads)

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

void* task(void* arg) {
    int id = *(int*)arg;
    printf("Thread %d running in process\n", id);
    sleep(1);
    return NULL;
}

int main() {
    pthread_t t1, t2;
    int id1 = 1, id2 = 2;

    pthread_create(&t1, NULL, task, &id1);
    pthread_create(&t2, NULL, task, &id2);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    printf("All threads finished\n");
    return 0;
}

Here one process creates two threads sharing memory.


4. Diagram – Comparison

Multiprocessing:               Multithreading:

+-------------------+          +-------------------+
| Process A (PID 1) |          |   Process X (PID) |
| Code/Data/Heap    |          |  Code/Data/Heap   |
+-------------------+          | +---------------+ |
                               | | Thread 1      | |
+-------------------+          | | Thread 2      | |
| Process B (PID 2) |          | | Thread 3      | |
| Code/Data/Heap    |          | +---------------+ |
+-------------------+          +-------------------+