DEV Community

Ank
Ank

Posted on • Edited on

What is FiFo algo?

Algorithm: FIFO (First In, First Out) Ticket Algorithm

Objective:
To ensure that processes (or threads) access a shared resource in the exact order they requested it — maintaining fairness and avoiding starvation.

  1. Concept Overview The FIFO Ticket Algorithm is a synchronization mechanism used in concurrent systems. Each process gets a ticket number when it requests access to a critical section. Processes are served in increasing order of their ticket numbers — just like people waiting in line for tickets.

2.** Data Structures**
ticket: A shared integer counter that gives out unique ticket numbers.
**turn: **A shared integer indicating the ticket number currently being served.

`my_ticket[i]: The ticket number assigned to process i.

  1. Initialization ticket = 0 turn = 0 for each process i: my_ticket[i] = -1
  1. Algorithm Steps
    Step 1: Request Entry (Entering Critical Section)

  2. my_ticket[i] = FetchAndIncrement(ticket)
    // Atomically assign a unique ticket number to process i

  3. while (my_ticket[i] != turn):
    wait() // Busy wait or block until it's this process's turn

Step 2: Execute Critical Section

  1. Perform critical section operations

Step 3: Exit Critical Section

  1. turn = turn + 1 // Allow the next ticket holder to enter`

5.** Practical Example
Scenario:**
Three customers (P1, P2, P3) want to buy tickets at a counter.
**
Result:**
All customers are served in the exact order they arrived — no starvation, no priority inversion.

  1. Key Properties Fairness: Guaranteed — first requester is first served. Mutual Exclusion: Only one process in the critical section at a time. Bounded Waiting: Each process waits a finite time. Simplicity: Easy to implement using atomic operations.
  2. Practical Implementation Note In real systems, the FetchAndIncrement() operation is implemented using atomic CPU instructions (like atomic_fetch_add() in C/C++). For distributed systems, ticket counters can be managed using centralized servers or distributed consensus mechanisms.

End of Algorithm

Top comments (0)