Print in Order Problem
Description
LeetCode Problem 1114.
Suppose we have a class:
public class Foo {
public void first() { print("first"); }
public void second() { print("second"); }
public void third() { print("third"); }
}
The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().
Note:
We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seem to imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness.
Example 1:
Input: nums = [1,2,3]
Output: "firstsecondthird"
Explanation: There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). "firstsecondthird" is the correct output.
Example 2:
Input: nums = [1,3,2]
Output: "firstsecondthird"
Explanation: The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). "firstsecondthird" is the correct output.
Constraints:
numsis a permutation of[1, 2, 3].
Solution
Approach: Two semaphores as a relay
The threads can start in any order, so second and third must be able to wait for their predecessor. Use two semaphores that start with zero permits:
firstprints, then releasesafterFirst.secondfirst acquiresafterFirst(blocking untilfirstis done), prints, then releasesafterSecond.thirdacquiresafterSecond, then prints.
The permits form a one-way chain, so the order is forced no matter how the scheduler interleaves the threads. Because a semaphore remembers a release, it does not matter if first finishes before second even starts.
Complexity: each method does O(1) work and the class uses O(1) extra space.
from threading import Semaphore
class Foo:
def __init__(self):
self.after_first = Semaphore(0)
self.after_second = Semaphore(0)
def first(self, printFirst: 'Callable[[], None]') -> None:
printFirst()
self.after_first.release()
def second(self, printSecond: 'Callable[[], None]') -> None:
self.after_first.acquire()
printSecond()
self.after_second.release()
def third(self, printThird: 'Callable[[], None]') -> None:
self.after_second.acquire()
printThird()