Skip to content

Instantly share code, notes, and snippets.

@yangmillstheory
Last active May 17, 2018 05:28
Show Gist options
  • Save yangmillstheory/c1c3cb9ebc8127f612edff4ee96f903b to your computer and use it in GitHub Desktop.
Save yangmillstheory/c1c3cb9ebc8127f612edff4ee96f903b to your computer and use it in GitHub Desktop.
Dining philosopher's problem.
import threading
import time
import logging
logging.basicConfig(
format='%(threadName)s: %(message)s', level=logging.DEBUG)
logger = logging.getLogger(__name__)
n = 5
forks = [threading.Lock() for _ in range(n)]
def p(i):
j = (i+1) % n
i, j = min(i, j), max(i, j) # without this line, we reach deadlock!
while True:
logger.info('thinking')
time.sleep(0)
logger.info('taking first fork {}'.format(i))
with forks[i]:
logger.info('took first fork; taking second fork {}'.format(j))
with forks[j]:
logger.info('took second fork {}; eating'.format(j))
time.sleep(0)
logger.info('done eating')
if __name__ == '__main__':
for i in range(n):
t = threading.Thread(
name='p-{}'.format(i), target=p, args=(i,))
t.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment