1279. Traffic Light Controlled Intersection - cocoder39/coco39_LC GitHub Wiki
1279. Traffic Light Controlled Intersection
from threading import Lock
class TrafficLight:
def __init__(self):
self.green = 1
self.lock = Lock()
def carArrived(
self,
carId: int, # ID of the car
roadId: int, # ID of the road the car travels on. Can be 1 (road A) or 2 (road B)
direction: int, # Direction of the car
turnGreen: 'Callable[[], None]', # Use turnGreen() to turn light to green on current road
crossCar: 'Callable[[], None]' # Use crossCar() to make car cross the intersection
) -> None:
with self.lock:
if roadId != self.green:
turnGreen()
self.green = roadId
crossCar()
def foo():
with lock:
# only one thread can execute code there
==
def foo():
lock.acquire()
try:
# only one thread can execute code there
finally:
lock.release() #release lock