Grokking Multithreading and Concurrency for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Problem 8: ZeroEvenOdd Multithreading Problem
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Overview

In the ZeroEvenOdd problem, we aim to print a sequence in the format "01020304...". The challenge is that we have three different threads responsible for printing parts of this sequence: one prints zeros, one prints even numbers, and one prints odd numbers. Proper synchronization between these threads is crucial to ensure the sequence is printed correctly and without race conditions. Our task is to structure and synchronize the threads to print this sequence up to 2n collaboratively.

Step-by-step Algorithm

  1. Initialize

    • Start with the first number (0).
    • Set up synchronization tools (locks, conditions, etc.).
  2. Thread A (Zero Printer)

    • Responsible for printing zeros.
  3. Thread B (Even Number Printer)

    • Prints even numbers in sequence.
  4. Thread C (Odd Number Printer)

    • Prints odd numbers in sequence.
  5. Synchronization

    • Ensure Thread A runs first, followed by either Thread B or Thread C based on whether the next number is even or odd.
  6. Wrap-up

    • Continue until the sequence length reaches 2n.

Algorithm Walkthrough

Assume n = 2. Our sequence should be "0102".

  1. Initialization:
    • Set n = 2.
    • Initialize counter = 1.
  2. Zero Printing (zero() function):
    • Print "0" because it's the starting character of the sequence.
  3. Odd Printing (odd() function):
    • Since counter is 1 (odd), this thread prints "1".
    • Increment counter to 2.
    • Signal to the Zero thread by unlocking zero_lock.
  4. Zero Printing (zero() function):
    • Print "0" following the odd number.
  5. Even Printing (even() function):
    • With counter at 2 (even), this thread prints "2".
    • Signal the end of the sequence as counter now equals n.

Synchronization Explained

  • Zero Thread: No lock initially. Prints "0" and signals the Odd thread if the counter is odd, or the Even thread if counter is even, by unlocking the respective lock.
  • Odd Thread: Initially locked. Waits for the Zero thread to signal. When unlocked, prints the odd number, increments counter, and signals back to the Zero thread by unlocking zero_lock.
  • Even Thread: Initially locked. Waits for the Zero thread to signal after an odd number has been printed. When unlocked, prints the even number and signals back to the Zero thread.
mediaLink

1 of 5

Python3
Python3

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible