Last active
May 17, 2018 05:28
-
-
Save yangmillstheory/c1c3cb9ebc8127f612edff4ee96f903b to your computer and use it in GitHub Desktop.
Dining philosopher's problem.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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